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

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<div class="breadcrumbs text-center mb-4">
    <h5 class="text-primary font-weight-bold"><i class="fa fa-user-shield"></i> Personal de Seguridad</h5>
    <p class="text-muted">Gestión de guardias, vigilantes y supervisores</p>
</div>

<div class="content mt-3">
    <div class="animated fadeIn">
        <div class="card shadow-sm border-0">
            <div class="card-header d-flex justify-content-between align-items-center flex-wrap">
                <h5 class="mb-0"><i class="fa fa-users"></i> Lista de Personal</h5>
                <button class="btn btn-light text-primary border-primary" data-toggle="modal" data-target="#modalAgregar">
                    <i class="fa fa-plus-circle"></i> Nuevo Personal
                </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="tablaPersonal" class="table table-striped table-hover nowrap text-center" style="width:100%">
                        <thead class="bg-primary text-white">
                            <tr>
                                <th>#</th>
                                <th>Acciones</th>
                                <th>Documento</th>
                                <th>Nombre Completo</th>
                                <th>Cargo</th>
                                <th>Turno</th>
                                <th>Celular</th>
                                <th>Fecha Ingreso</th>
                                <th>Estado</th>
                                <th>Creado</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            include '../config/conexion.php';
                            $database = new Connection();
                            $db = $database->open();
                            try {
                                $sql = "SELECT * FROM personal_seguridad ORDER BY id DESC";
                                foreach ($db->query($sql) as $row): ?>
                                    <tr>
                                        <td><?= $row['id']; ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" 
                                                    onclick="openEditModal(<?= $row['id']; ?>, '<?= $row['nro_documento']; ?>', '<?= $row['nombre_completo']; ?>', '<?= $row['cargo']; ?>', '<?= $row['turno']; ?>', '<?= $row['nro_celular']; ?>', '<?= $row['fecha_ingreso']; ?>', '<?= $row['estado']; ?>')">
                                                    <i class="fa fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" 
                                                    onclick="confirmDelete(<?= $row['id']; ?>, '<?= $row['nombre_completo']; ?>')">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                        <td><?= $row['nro_documento']; ?></td>
                                        <td><?= $row['nombre_completo']; ?></td>
                                        <td><?= $row['cargo']; ?></td>
                                        <td><span class="badge badge-info"><?= $row['turno']; ?></span></td>
                                        <td><?= $row['nro_celular']; ?></td>
                                        <td><?= date('d/m/Y', strtotime($row['fecha_ingreso'])); ?></td>
                                        <td>
                                            <span class="badge <?= $row['estado'] == 'Activo' ? 'badge-success' : 'badge-secondary'; ?>">
                                                <?= $row['estado']; ?>
                                            </span>
                                        </td>
                                        <td><?= date('d/m/Y', strtotime($row['fecha_creacion'])); ?></td>
                                    </tr>
                            <?php endforeach;
                            } catch (PDOException $e) {
                                echo "<tr><td colspan='10'>Error: " . $e->getMessage() . "</td></tr>";
                            }
                            $database->close();
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../modal/seguridad.php'; ?>
<?php include 'footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
new DataTable('#tablaPersonal', {
    responsive: true,
    language: { url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json' }
});

function confirmDelete(id, name) {
  Swal.fire({
    title: '¿Eliminar Personal?',
    html: `Se eliminará a <b>${name}</b> de la lista.`,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Sí, eliminar',
    cancelButtonText: 'Cancelar',
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
  }).then((result) => {
    if (result.isConfirmed) {
      window.location.href = `../controller/delete_personal.php?id=${id}`;
    }
  });
}

</script>

<script>
function openEditModal(id, documento, nombre, cargo, turno, celular, ingreso, estado) {
    // Llenar el formulario con los valores
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_nro_documento').value = documento;
    document.getElementById('edit_nombre_completo').value = nombre;
    document.getElementById('edit_cargo').value = cargo;
    document.getElementById('edit_turno').value = turno;
    document.getElementById('edit_nro_celular').value = celular;
    document.getElementById('edit_fecha_ingreso').value = ingreso;
    document.getElementById('edit_estado').value = estado;

    // Mostrar el modal (detecta si es Bootstrap 4 o 5)
    const modalId = 'modalEditar';
    const modalElement = document.getElementById(modalId);

    if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
        // Bootstrap 4 con jQuery
        $('#' + modalId).modal('show');
    } else if (typeof bootstrap !== 'undefined') {
        // Bootstrap 5 sin jQuery
        const modal = new bootstrap.Modal(modalElement);
        modal.show();
    } else {
        console.error('No se encontró Bootstrap ni jQuery para abrir el modal.');
    }
}
</script>
