<?php include 'header.php'; ?>


<style>
body {
    background-color: #f4f6f9;
}

/* Card principal */
.card {
    border: none;
    border-radius: 1rem;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}

/* Encabezado */
.card-header {
    background: linear-gradient(90deg, #007bff, #00bcd4);
    color: #fff;
    font-weight: 600;
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
    padding: 1rem 1.5rem;
}

.card-header .btn {
    font-weight: 600;
    border-radius: 8px;
}

/* Botones */
.btn-success {
    background: linear-gradient(90deg, #28a745, #20c997);
    border: none;
}
.btn-success:hover {
    background: linear-gradient(90deg, #20c997, #28a745);
    transform: scale(1.05);
}

/* Tabla */
.table {
    border-radius: 10px;
    overflow: hidden;
}
.table thead {
    background: linear-gradient(90deg, #007bff, #00bcd4);
    color: #fff;
    font-size: 14px;
    text-transform: uppercase;
}
.table-hover tbody tr:hover {
    background-color: #e3f2fd !important;
    transition: all 0.2s ease;
}

/* Botones de acción */
.btn-outline-primary, .btn-outline-danger {
    border-radius: 8px;
    transition: 0.3s;
}
.btn-outline-primary:hover {
    background: #007bff;
    color: white;
}
.btn-outline-danger:hover {
    background: #dc3545;
    color: white;
}

/* Animación de la tabla */
tbody tr {
    transition: transform 0.15s ease-in-out;
}
tbody tr:hover {
    transform: scale(1.01);
}

/* Etiquetas */
.badge {
    font-size: 0.8rem;
    border-radius: 8px;
}

/* Breadcrumbs */
.breadcrumbs {
    background: none;
}
.breadcrumb {
    background: transparent;
    margin-bottom: 0;
}
.breadcrumb li a {
    color: #007bff;
    text-decoration: none;
}
.breadcrumb li.active {
    color: #333;
}
</style>

<div class="breadcrumbs text-center mb-4">
    <h5 class="text-primary font-weight-bold"><i class="fa fa-truck"></i> Gestión de Flota Vehicular</h5>
    <p class="text-muted">Control y registro de todos los vehículos operativos</p>
</div>

<div class="content mt-3">
    <div class="animated fadeIn">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center flex-wrap">
                        <h5 class="mb-0"><i class="fa fa-car-side"></i> Lista de Vehículos</h5>
                        <button type="button" class="btn btn-light text-primary border-primary" data-toggle="modal" data-target="#largeModal">
                            <i class="fa fa-plus-circle"></i> Nuevo Vehículo
                        </button>
                    </div>

                    <?php if (isset($_SESSION['message'])): ?>
                        <div class="alert alert-success text-center mt-2">
                            <?= $_SESSION['message']; unset($_SESSION['message']); ?>
                        </div>
                    <?php endif; ?>

                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="example" class="table table-striped table-hover nowrap align-middle" style="width:100%">
                                <thead>
                                    <tr class="text-center">
                                        <th>#</th>
                                        <th>Acciones</th>
                                        <th>Tipo</th>
                                        <th>Marca</th>
                                        <th>Modelo</th>
                                        <th>Placa</th>
                                        <th>Nro. Serie</th>
                                        <th>Color</th>
                                        <th>Año</th>
                                        <th>Carga Máx.</th>
                                        <th>Combustible</th>
                                        <th>Aceite</th>
                                        <th>Litros Aceite</th>
                                        <th>Creado</th>
                                    </tr>
                                </thead>
                                <tbody class="text-center">
                                    <?php
                                    include '../config/conexion.php';
                                    $database = new Connection();
                                    $db = $database->open();
                                    try {
                                        $sql = 'SELECT * FROM flota';
                                        foreach ($db->query($sql) as $row): ?>
                                            <tr>
                                                <td><strong><?= $row['id']; ?></strong></td>
                                                <td>
                                                    <div class="btn-group btn-group-sm" role="group">
                                                        <button class="btn btn-outline-danger btn-sm" onclick="confirmDelete(<?= $row['id']; ?>, '<?= $row['placa']; ?>')" title="Eliminar">
    <i class="fa fa-trash"></i>
</button>

                                                                                        <button 
                                    class="btn btn-outline-primary btn-sm" 
                                    title="Editar"
                                    onclick="openEditVehiculo(
                                        <?= $row['id']; ?>,
                                        '<?= htmlspecialchars($row['tipo']); ?>',
                                        '<?= htmlspecialchars($row['marca']); ?>',
                                        '<?= htmlspecialchars($row['modelo']); ?>',
                                        '<?= htmlspecialchars($row['placa']); ?>',
                                        '<?= htmlspecialchars($row['nro_serie']); ?>',
                                        '<?= htmlspecialchars($row['ano']); ?>',
                                        '<?= htmlspecialchars($row['carga_maxima']); ?>',
                                        '<?= htmlspecialchars($row['tipo_combustible']); ?>',
                                        '<?= htmlspecialchars($row['tipo_de_aceite']); ?>',
                                        '<?= htmlspecialchars($row['cantidad_aceite']); ?>'
                                    )">
                                    <i class="fa fa-edit"></i>
                                    </button>
                                                    </div>
                                                </td>
                                                <td><span class="badge badge-info"><?= $row['tipo']; ?></span></td>
                                                <td><?= $row['marca']; ?></td>
                                                <td><?= $row['modelo']; ?></td>
                                                <td><strong><?= $row['placa']; ?></strong></td>
                                                <td><?= $row['nro_serie']; ?></td>
                                                <td><span class="badge badge-light border"><?= $row['color']; ?></span></td>
                                                <td><?= $row['ano']; ?></td>
                                                <td><?= $row['carga_maxima']; ?> kg</td>
                                                <td><?= $row['tipo_combustible']; ?></td>
                                                <td><?= $row['tipo_de_aceite']; ?></td>
                                                <td><?= $row['cantidad_aceite']; ?> L</td>
                                                <td><?= date('d/m/Y', strtotime($row['fecha_creacion'])); ?></td>
                                            </tr>
                                    <?php endforeach;
                                    } catch(PDOException $e) {
                                        echo "<tr><td colspan='14'>Error: " . $e->getMessage() . "</td></tr>";
                                    }
                                    $database->close();
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div> <!-- animated -->
</div> <!-- content -->

<?php
include 'footer.php';
include '../modal/flota.php';
include '../modal/actualizar_flota.php';
?>

<!-- DataTables -->
<script>
new DataTable('#example', {
    responsive: true,
    layout: {
        topStart: {
            buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
        }
    },
    language: { url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json' }
});
</script>
<script>
window.openEditVehiculo = function(id, tipo, marca, modelo, placa, nro_serie, ano, carga_maxima, tipo_combustible, tipo_de_aceite, cantidad_aceite) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_tipo').value = tipo;
    document.getElementById('edit_marca').value = marca;
    document.getElementById('edit_modelo').value = modelo;
    document.getElementById('edit_placa').value = placa;
    document.getElementById('edit_nro_serie').value = nro_serie;
    document.getElementById('edit_ano').value = ano;
    document.getElementById('edit_carga_maxima').value = carga_maxima;
    document.getElementById('edit_tipo_combustible').value = tipo_combustible;
    document.getElementById('edit_tipo_de_aceite').value = tipo_de_aceite;
    document.getElementById('edit_cantidad_aceite').value = cantidad_aceite;

    if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
        $('#editVehiculoModal').modal('show');
    } else if (typeof bootstrap !== 'undefined') {
        const modal = new bootstrap.Modal(document.getElementById('editVehiculoModal'));
        modal.show();
    } else {
        alert('No se pudo abrir el modal: Bootstrap o jQuery no están cargados correctamente.');
    }
}
</script>

<script>
function confirmDelete(id, placa) {
  Swal.fire({
    title: '¿Eliminar vehículo?',
    html: `Se eliminará el vehículo con placa <b>${placa}</b>. Esta acción no se puede deshacer.`,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Sí, eliminar',
    cancelButtonText: 'Cancelar',
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
    reverseButtons: true
  }).then((result) => {
    if (result.isConfirmed) {
      // Redirige al controlador de eliminación
      window.location.href = `../controller/delete_vehiculo.php?id=${id}`;
    }
  });
}
</script>