<?php
// usuarios_ip.php — Vista mínima con botón "Borrar IP"
session_start();
require_once __DIR__ . '/conex.php';
$usuario = $_SESSION['usuario'] ?? 'admin';
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Usuarios · IP</title>

  <!-- Bootstrap 5 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <!-- DataTables (BS5) -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
  <!-- Font Awesome (para el ícono del borrador) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">

  <style>
    body { background:#f6f8fb; }
  </style>
</head>
<body>
  <div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">Usuarios &mdash; IP autorizada</h4>
      <small class="text-muted">Conectado: <?php echo htmlspecialchars($usuario, ENT_QUOTES, 'UTF-8'); ?></small>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="table-responsive">
          <table id="usuar" class="table table-striped table-hover w-100">
            <thead class="table-light">
              <tr>
                <th>Usuario</th>
                <th>Sucursal</th>
                <th>IP</th>
                <th>Acción</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
        <div class="text-secondary small mt-2">
          <i class="fa-solid fa-circle-info me-1"></i>
          Solo lectura. Usa el botón <em>Borrar IP</em> para limpiar la IP guardada.
        </div>
      </div>
    </div>
  </div>

  <!-- JS base -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
  <!-- SweetAlert2 -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
    $(function(){
      const table = $("#usuar").DataTable({
        deferRender: true,
        stateSave: true,
        paging: true,
        lengthChange: false,
        searching: true,
        autoWidth: false,
        ajax: {
          url: "funcion_usuarios_ip.php",
          type: "POST",
          dataSrc: function (json) {
            return Array.isArray(json?.data) ? json.data : [];
          },
          error: function () {
            Swal.fire("Error", "No se pudieron cargar los datos.", "error");
          }
        },
        columns: [
          { data: "usuario",  className: "text-center" },
          { data: "sucursal", className: "text-center" },
          { data: "ip",       className: "text-center",
            render: function(d){
              const t = (d||'').toString();
              const esc = $('<div>').text(t).html(); // escapar
              return esc || '<span class="text-muted">—</span>';
            }
          },
          { data: null, orderable:false, searchable:false, className:"text-center",
            render: function(_, __, row){
              const userEsc = $('<div>').text(row.usuario || '').html();
              const ipEsc   = $('<div>').text(row.ip || '').html();
              const disabled = (row.ip ? '' : 'disabled');
              return `
                <button class="btn btn-sm btn-outline-danger btn-clear-ip"
                        title="Borrar IP"
                        data-id="${row.idusuario}"
                        data-usuario="${userEsc}"
                        data-ip="${ipEsc}"
                        ${disabled}>
                  <i class="fa-solid fa-eraser me-1"></i> Borrar IP
                </button>
              `;
            }
          }
        ],
        language: {
          zeroRecords: "No se encontraron resultados",
          emptyTable: "Ningún dato disponible",
          info: "Mostrando _START_–_END_ de _TOTAL_",
          infoEmpty: "Mostrando 0–0 de 0",
          search: "Buscar:",
          paginate: { first:"Primero", last:"Último", next:"Siguiente", previous:"Anterior" }
        }
      });

      // Borrar IP
      $('#usuar').on('click', '.btn-clear-ip', function () {
        const $btn = $(this);
        if ($btn.prop('disabled')) return;

        const id   = $btn.data('id');
        const user = $btn.data('usuario') || '';
        const ip   = $btn.data('ip') || '';

        Swal.fire({
          icon: 'question',
          title: 'Borrar IP',
          html: '¿Deseas borrar la IP <b>' + (ip || '(vacía)') + '</b> del usuario <b>' + user + '</b>?',
          showCancelButton: true,
          confirmButtonText: 'Sí, borrar',
          cancelButtonText: 'Cancelar'
        }).then(function (res) {
          if (!res.isConfirmed) return;

          $.post('usuarios_clear_ip.php', { id: id }, function (r) {
            if (r && r.success) {
              Swal.fire({ icon: 'success', title: 'IP borrada', timer: 1200, showConfirmButton: false });
              table.ajax.reload(null, false);
            } else {
              Swal.fire({ icon: 'error', title: 'Error', text: (r && r.message) ? r.message : 'No se pudo borrar la IP' });
            }
          }, 'json').fail(function () {
            Swal.fire({ icon: 'error', title: 'Error', text: 'Fallo de red o servidor' });
          });
        });
      });
    });
  </script>
</body>
</html>
