<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$results_per_page = 10;

$page = isset($_GET['view']) ? (int)$_GET['view'] : 1;
$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('a/.eggziedb.db');

$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $st = SQLite3::escapeString($searchTerm);
    $searchQuery = "WHERE mac_address LIKE '%$st%' OR title LIKE '%$st%' OR username LIKE '%$st%'";
}

$result   = $db1->query("SELECT COUNT(id) AS total FROM ibo $searchQuery");
$rownew   = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($totaleview / $results_per_page);
$res1 = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id DESC LIMIT $start_from, $results_per_page");

if (isset($_GET['delete'])) {
    $db1->exec('DELETE FROM ibo WHERE id=' . (int)$_GET['delete']);
    header('Location: users.php');
    exit;
}

if (isset($_POST['bulk_dns_submit'])) {
    $new_dns = trim($_POST['new_bulk_dns']);
    $ids     = isset($_POST['selected_ids']) ? $_POST['selected_ids'] : [];
    if (!empty($new_dns) && !empty($ids)) {
        $ids_escaped = implode(',', array_map('intval', $ids));
        $new_dns_safe = SQLite3::escapeString($new_dns);
        $db1->exec("UPDATE ibo SET url='$new_dns_safe' WHERE id IN ($ids_escaped)");
    }
    header('Location: users.php');
    exit;
}

$total_all = $db1->querySingle("SELECT COUNT(id) FROM ibo") ?: 0;
$expiring  = $db1->querySingle("SELECT COUNT(id) FROM ibo WHERE expire_date <= date('now','+7 days') AND expire_date >= date('now')") ?: 0;
$expired   = $db1->querySingle("SELECT COUNT(id) FROM ibo WHERE expire_date < date('now')") ?: 0;

include 'includes/header.php';
?>

<!-- Delete Modal -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h2><i class="fas fa-exclamation-triangle" style="color:var(--danger)"></i> Confirmar</h2>
      </div>
      <div class="modal-body">Deseja realmente excluir este cliente?</div>
      <div class="modal-footer" style="gap:8px">
        <button type="button" class="u-btn u-btn-ghost u-btn-sm" data-dismiss="modal">Cancelar</button>
        <a class="u-btn u-btn-danger u-btn-sm btn-ok">Excluir</a>
      </div>
    </div>
  </div>
</div>

<!-- Page Header -->
<div class="page-header flex items-center justify-between flex-wrap gap-3">
  <div>
    <h1><i class="fas fa-users" style="color:var(--accent);font-size:18px"></i> Clientes</h1>
    <p>Gerencie todos os usuários cadastrados no sistema.</p>
  </div>
  <a href="./users_create.php" class="u-btn u-btn-primary">
    <i class="fas fa-plus"></i> Novo Cliente
  </a>
</div>

<!-- Stat Chips -->
<div class="grid-3 mb-4">
  <div class="stat-chip">
    <div class="stat-chip-icon cyan"><i class="fas fa-users"></i></div>
    <div class="stat-chip-info">
      <div class="stat-chip-value"><?php echo $total_all; ?></div>
      <div class="stat-chip-label">Total de Clientes</div>
    </div>
  </div>
  <div class="stat-chip">
    <div class="stat-chip-icon violet"><i class="fas fa-clock"></i></div>
    <div class="stat-chip-info">
      <div class="stat-chip-value"><?php echo $expiring; ?></div>
      <div class="stat-chip-label">Vencem em 7 dias</div>
    </div>
  </div>
  <div class="stat-chip">
    <div class="stat-chip-icon red"><i class="fas fa-times-circle"></i></div>
    <div class="stat-chip-info">
      <div class="stat-chip-value"><?php echo $expired; ?></div>
      <div class="stat-chip-label">Expirados</div>
    </div>
  </div>
</div>

<!-- Main Card -->
<div class="u-card accent-left glow">
  <div class="u-card-header">
    <span class="u-card-title"><i class="fas fa-table"></i> Lista de Clientes
      <?php if (!empty($searchTerm)): ?>
        <span class="u-badge u-badge-cyan" style="margin-left:6px"><?php echo $totaleview; ?> resultado(s)</span>
      <?php endif; ?>
    </span>
    <!-- Search inline -->
    <form method="get" style="width:260px;max-width:100%">
      <div class="search-bar">
        <i class="fas fa-search"></i>
        <input type="text" name="search" placeholder="Buscar MAC, título, usuário…"
               value="<?php echo htmlspecialchars($searchTerm); ?>">
        <button type="submit">Buscar</button>
      </div>
    </form>
  </div>

  <div class="u-card-body">

    <!-- ── Bulk DNS form wrapper ── -->
    <form method="post" id="bulk-form">

      <!-- Bulk Bar -->
      <div id="bulk-dns-bar">
        <div class="bulk-label">
          <i class="fas fa-globe"></i>
          DNS em Massa &mdash;
          <span class="cnt" id="bulk-count">0</span> selecionado(s)
        </div>
        <input type="text" name="new_bulk_dns" class="u-input"
               placeholder="Novo DNS (ex: http://servidor.com)" required>
        <button type="submit" name="bulk_dns_submit" class="u-btn u-btn-warning">
          <i class="fas fa-sync-alt"></i> Aplicar
        </button>
        <button type="button" class="u-btn u-btn-ghost" onclick="deselectAll()">
          <i class="fas fa-times"></i> Cancelar
        </button>
      </div>

      <div class="u-table-wrap">
        <table class="u-table">
          <thead>
            <tr>
              <th style="width:36px">
                <input type="checkbox" class="u-check" id="check-all" title="Selecionar todos">
              </th>
              <th>Título</th>
              <th>MAC Address</th>
              <th>Usuário</th>
              <th>Expiração</th>
              <th>DNS</th>
              <th style="width:110px;text-align:center">Ações</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row1 = $res1->fetchArray()):
              $uid   = $row1['id'];
              $uexp  = $row1['expire_date'];
              $today = date('Y-m-d');
              $expClass = '';
              if ($uexp < $today) $expClass = 'u-badge u-badge-red';
              elseif ($uexp <= date('Y-m-d', strtotime('+7 days'))) $expClass = 'u-badge u-badge-orange';
              else $expClass = 'u-badge u-badge-green';
            ?>
            <tr>
              <td>
                <input type="checkbox" class="u-check row-check"
                       name="selected_ids[]" value="<?php echo $uid; ?>">
              </td>
              <td style="max-width:140px">
                <strong><?php echo htmlspecialchars($row1['title']); ?></strong>
              </td>
              <td>
                <code><?php echo htmlspecialchars($row1['mac_address']); ?></code>
              </td>
              <td><?php echo htmlspecialchars($row1['username']); ?></td>
              <td>
                <span class="<?php echo $expClass; ?>">
                  <?php echo htmlspecialchars($uexp); ?>
                </span>
              </td>
              <td style="max-width:180px">
                <span style="font-size:12px;color:var(--text-muted);word-break:break-all">
                  <?php echo htmlspecialchars($row1['url']); ?>
                </span>
              </td>
              <td>
                <div style="display:flex;gap:6px;justify-content:center">
                  <!-- Edit -->
                  <a class="u-btn u-btn-ghost u-btn-icon"
                     href="./users_update.php?update=<?php echo $uid; ?>"
                     title="Editar">
                    <i class="fas fa-pencil-alt" style="color:var(--accent)"></i>
                  </a>
                  <!-- Duplicate -->
                  <a class="u-btn u-btn-ghost u-btn-icon"
                     href="./users_duplicate.php?dup=<?php echo $uid; ?>"
                     title="Duplicar">
                    <i class="fas fa-copy" style="color:var(--orange)"></i>
                  </a>
                  <!-- Delete -->
                  <a class="u-btn u-btn-ghost u-btn-icon delete-btn" href="#"
                     data-href="./users.php?delete=<?php echo $uid; ?>"
                     data-toggle="modal" data-target="#confirm-delete"
                     title="Excluir">
                    <i class="fas fa-trash-alt" style="color:var(--danger)"></i>
                  </a>
                </div>
              </td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div><!-- /table-wrap -->

    </form><!-- /bulk-form -->

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="u-pagination">
      <?php if ($page > 1): ?>
        <a class="u-page-btn" href="users.php?view=<?php echo $page-1; ?><?php echo $searchTerm ? '&search='.urlencode($searchTerm) : ''; ?>">
          <i class="fas fa-chevron-left"></i>
        </a>
      <?php endif; ?>
      <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <a class="u-page-btn <?php echo $i == $page ? 'active' : ''; ?>"
           href="users.php?view=<?php echo $i; ?><?php echo $searchTerm ? '&search='.urlencode($searchTerm) : ''; ?>">
          <?php echo $i; ?>
        </a>
      <?php endfor; ?>
      <?php if ($page < $total_pages): ?>
        <a class="u-page-btn" href="users.php?view=<?php echo $page+1; ?><?php echo $searchTerm ? '&search='.urlencode($searchTerm) : ''; ?>">
          <i class="fas fa-chevron-right"></i>
        </a>
      <?php endif; ?>
    </div>
    <p style="font-size:12px;color:var(--text-muted);margin-top:8px">
      Exibindo <?php echo min($start_from + $results_per_page, $totaleview); ?> de <?php echo $totaleview; ?> registros
    </p>
    <?php endif; ?>

  </div><!-- /card-body -->
</div><!-- /card -->

<script>
document.getElementById('check-all').addEventListener('change', function(){
    document.querySelectorAll('.row-check').forEach(cb => cb.checked = this.checked);
    updateBar();
});
document.querySelectorAll('.row-check').forEach(cb => cb.addEventListener('change', updateBar));

function updateBar(){
    var n = document.querySelectorAll('.row-check:checked').length;
    document.getElementById('bulk-count').textContent = n;
    var bar = document.getElementById('bulk-dns-bar');
    n > 0 ? bar.classList.add('show') : bar.classList.remove('show');
    if (!n) document.getElementById('check-all').checked = false;
}
function deselectAll(){
    document.querySelectorAll('.row-check, #check-all').forEach(cb => cb.checked = false);
    updateBar();
}
</script>

<?php
include 'includes/footer.php';
require 'includes/egz.php';
?>
