<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$db1 = new SQLite3('./api/.db.db');
$searchQuery = "SELECT * FROM ibo WHERE 1=1";
if (!empty($searchTerm)) {
$searchQuery .= " AND (mac_address = '$searchTerm' OR title = '$searchTerm')";
} else {
$searchQuery .= " AND 0";
}
$res1 = $db1->query($searchQuery);
if (isset($_GET['delete'])) {
$id = intval($_GET['delete']);
$stmt = $db1->prepare("SELECT mac_address FROM ibo WHERE id = :id");
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
if ($row) {
$mac = $row['mac_address'];
// Eliminar
$db1->exec("DELETE FROM ibo WHERE id = $id");
$db1->exec("DELETE FROM subscription WHERE mac_address = '" . SQLite3::escapeString($mac) . "'");
    }
// Redirigir con mensaje de éxito
header("Location: buscar_users.php?deleted=1");
exit;
    }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Editar Clientes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://kit.fontawesome.com/4fa1f3b6b2.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="css/rgvip.css">
<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <style>
        body {
  background: linear-gradient(to right, #0f2027, #203a43, #2c5364);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
}
 .card {
  background-color: #1e1e2f;
  padding: 20px;
  border-top: 5px solid #0A38D1;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
  text-align: center;
        }
  .btn-primary {
  background-color: #2a5298;
  border: none;
        }
  .btn-primary:hover {
  background-color: #1e3c72;
        }
        h2 {
  font-size: 22px;
  color: white;
  margin-bottom: 20px;
    }
        #logo {
  max-width: 30%;
  height: auto;
  margin: 0 auto 20px;
  animation: neonGlow 1.5s ease-in-out infinite alternate;
    }

 /* Animación de resplandor para el logo */
    @keyframes neonGlow {
      0% {
        filter: drop-shadow(0 0 5px #0A38D1) drop-shadow(0 0 10px #0A38D1) drop-shadow(0 0 20px #0A38D1);
        transform: scale(1);
      }
      50% {
        filter: drop-shadow(0 0 15px #0A38D1) drop-shadow(0 0 30px #0A38D1) drop-shadow(0 0 50px #0A38D1);
        transform: scale(1.05);
      }
      100% {
        filter: drop-shadow(0 0 5px #0A38D1) drop-shadow(0 0 10px #0A38D1) drop-shadow(0 0 20px #0A38D1);
        transform: scale(1);
      }
        h3.text-center {
    color: white;
}
label.form-label {
    color: white;
}
    </style>
</head>
<body>
    <!-- Modal de confirmación -->
<div class="modal fade" id="confirm-delete" tabindex="-1" aria-labelledby="confirmDeleteLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content text-dark">
      <div class="modal-header">
        <h5 class="modal-title" id="confirmDeleteLabel">Confirmar eliminación</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        ¿Realmente deseas eliminar este usuario?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
        <a href="#" class="btn btn-danger btn-ok">Eliminar</a>
      </div>
    </div>
  </div>
</div>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        var confirmModal = document.getElementById('confirm-delete');
        confirmModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var href = button.getAttribute('data-href');
            var deleteBtn = confirmModal.querySelector('.btn-ok');
            deleteBtn.setAttribute('href', href);
        });
    });
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    function formatMacInput(input) {
        input.addEventListener("input", function(e) {
            var value = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
            var formatted = "";
            for (var i = 0; i < value.length; i++) {
                formatted += value[i];
                if ((i + 1) % 2 === 0 && i < value.length - 1) {
                    formatted += ":";
                }
            }
            e.target.value = formatted;
        });
    }

    formatMacInput(document.querySelector('.mac-input'));

    document.getElementById('add_mac_field').addEventListener('click', function () {
        var container = document.getElementById('mac_fields');
        var newInputGroup = document.createElement('div');
        newInputGroup.classList.add('input-group', 'mt-2');
        newInputGroup.innerHTML = <input class="form-control text-primary mac-input" name="mac_address[]" type="text" placeholder="Enter MAC Address" required/>;
        container.appendChild(newInputGroup);
        formatMacInput(newInputGroup.querySelector('.mac-input'));
    });
});
</script>
<div class="card border-left-primary shadow h-100 card shadow mb-4">
<div class="card-header py-3">
<h2>EDITAR CLIENTES</h2>
<?php
$logoPath = ''; // Inicializa vacío
$jsonPath = './logo/filenames.json';
if (file_exists($jsonPath)) {
$jsonData = file_get_contents($jsonPath);
$imageData = json_decode($jsonData, true);
if (!empty($imageData[0]['ImageName'])) {
if ($imageData[0]['Upload_type'] === 'by_file') {
$logoPath = './logo/' . $imageData[0]['ImageName'];
} elseif ($imageData[0]['Upload_type'] === 'by_url') {
$logoPath = $imageData[0]['ImageName'];
}
}
}
?>
<?php if (!empty($logoPath)): ?>
<img id="logo" src="<?= htmlspecialchars($logoPath) ?>" alt="Logo">
<?php endif; ?>
<h6 class="card-title-dark text-white"><i class="fa fa-fw fa-user-plus"></i>Ingresa la MAC para editar un cliente registrado. Si es un cliente nuevo puedes Generar un Código de Activación</h6>
</div>
<div class="card-body">
<?php if (isset($_GET['deleted'])): ?>
<?php if ($_GET['deleted'] == 1): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
🗑️ Cliente eliminado correctamente.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
</div>
<?php else: ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
❌ No se pudo eliminar el cliente. Intenta nuevamente.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if (isset($_GET['updated']) && $_GET['updated'] == 1): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        ✅ Cliente actualizado correctamente.
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
    </div>
<?php endif; ?>
<form method="get" class="mb-3">
<div class="form-group">
<div class="input-group">
<input type="text" name="search" class="form-control mac-input" placeholder="Ingresa aquí la MAC" value="<?= htmlspecialchars($searchTerm) ?>">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">🔎Buscar</button>
</div>
</div>
</div>
</form>
<div class="form-group">
<div class="input-group">
<a href="./generar_publico.php" class="btn btn-primary btn-icon-split">
<span class="icon text-white-50"><i class="fas fa-check"></i></span>
<span class="text">🔑Generar Código</span>
</a>
</div>
</div>
<br>
<?php if (!empty($searchTerm)) { ?>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead class="text-color">
<tr>
<th>Nombre</th>
<th>Mac Address</th>
<th>Usuario</th>
<th>Expiración</th>
<th>DNS</th>
<th>Editar</th>
<th>Eliminar</th>
<th>Estado</th>
</tr>
</thead>
<tbody>
<?php
$found = false;
while ($row1 = $res1->fetchArray()) {
$found = true;
?>
<tr>
<td><?php echo $row1['title']; ?></td>
<td><?php echo $row1['mac_address']; ?></td>
<td><?php echo $row1['username']; ?></td>
<td><?php echo $row1['expire_date']; ?></td>
<td><?php echo $row1['url']; ?></td>
<!-- Botón Editar -->
<td>
    <a class="btn btn-icon" href="./update_public.php?update=<?php echo $row1['id']; ?>">
        <span class="icon text-white-50"><i class="fa fa-pencil-square" style="font-size:24px;color:blue"></i></span>
    </a>
</td>
<!-- Botón Eliminar -->
<td>
    <a class="btn btn-icon delete-btn" href="#" data-href="./buscar_users.php?delete=<?php echo $row1['id']; ?>" data-bs-toggle="modal" data-bs-target="#confirm-delete">
        <span class="icon text-white-50"><i class="fa fa-ban" style="font-size:24px;color:red"></i></span>
    </a>
</td>
<td>
<?php
$today = date('Y-m-d');
if ($row1['expire_date'] >= $today) {
echo '<span style="color:green;">✅Activo</span>';
} else {
echo '<span style="color:red;">❌Vencido</span>';
}
?>
</td>
</tr>
<?php } ?>
<?php if (!$found) { ?>
<tr><td colspan="8" class="text-center">No se encontró ningún registro con ese término de búsqueda.</td></tr>
<?php } ?>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
</main>