<?php include __DIR__ . '/includes/auth_guard.php'; ?>
<?php
/******************************************************************
 * user_manage.php — wrapper-safe (no $db->query() calls required)
 * Uses only: select, selectWithCount, insert, update, delete, insertIfEmpty
 ******************************************************************/
include('includes/header.php');

/* -------- Optional debug while testing -------- */
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

/* -------- Tiny helpers -------- */
function js_redirect(string $url): void { echo '<script>location.href='.json_encode($url).';</script>'; exit; }
function now_iso(): string { $tz=@date_default_timezone_get()?:'UTC'; date_default_timezone_set($tz); return date('Y-m-d H:i:s'); }
function new_plid(): string { $t=now_iso(); return hash('sha256', md5($t).$t); }

/* -------- Spinner guard for ?dups=1 -------- */ ?>
<style>
.no-spinner #spinner.show{display:none!important;opacity:0!important;visibility:hidden!important}
.badge-dup{background:#f0ad4e;color:#222;border-radius:10px;padding:2px 6px;font-size:12px}
@media (max-width:768px){.pagination .btn{padding:6px 10px;font-size:14px;margin-bottom:2px}}
</style>
<script>
(function(){if(location.search.indexOf('dups=1')!==-1){document.documentElement.classList.add('no-spinner');
document.addEventListener('DOMContentLoaded',function(){var sp=document.getElementById('spinner');if(sp&&sp.classList.contains('show'))sp.classList.remove('show');});}})();
</script>
<?php

/* -------- Inputs / constants -------- */
$table_name         = "ibof";
$table_name_advance = "devop";
$table_name_sort    = "sort";
$table_name_dns     = "dns";
$page_user          = "user_manage.php";
$pagemac            = "mac_manage.php";

$selected_uid   = $_GET['uuid'] ?? '';
$get_macaddress = $_GET['mac'] ?? '';

$currunt_page   = filter_input(INPUT_GET,'view',FILTER_VALIDATE_INT) ?: 1;
$selected_page  = $currunt_page>0 ? "&view=".$currunt_page : '';

$updateId = filter_input(INPUT_GET,'update',FILTER_VALIDATE_INT);
$deleteId = filter_input(INPUT_GET,'delete',FILTER_VALIDATE_INT);
$markId   = filter_input(INPUT_GET,'mark',FILTER_VALIDATE_INT);

$searchTerm  = isset($_GET['search']) ? trim((string)$_GET['search']) : '';
$searchParam = $searchTerm!=='' ? '&search='.urlencode($searchTerm) : '';
$showDups    = isset($_GET['dups']) && $_GET['dups']=='1';

$dupType = (isset($_GET['dup_type']) && in_array($_GET['dup_type'],['mac','user'])) ? $_GET['dup_type'] : '';
$dupKey  = isset($_GET['dup_key']) ? (string)urldecode($_GET['dup_key']) : '';

/* ============================================================
   BOOTSTRAP (optional, safe): create table / indexes IF POSSIBLE
   - Only runs if the wrapper exposes an 'exec' method.
   - If not present, it silently skips (no breakage).
============================================================ */
if (method_exists($db,'exec')) {
  try {
    $db->exec("CREATE TABLE IF NOT EXISTS ibof (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plid TEXT, name TEXT, macad TEXT, uuid TEXT, username TEXT, password TEXT,
      cdate TEXT, udate TEXT, mark INTEGER DEFAULT 0, protec INTEGER DEFAULT 1
    )");
    // Helpful indexes (ignore if wrapper/SQLite version doesn’t support expressions)
    try { $db->exec("CREATE INDEX IF NOT EXISTS idx_ibof_username ON ibof (username)"); } catch(Throwable $e){}
    try { $db->exec("CREATE INDEX IF NOT EXISTS idx_ibof_macad    ON ibof (macad)");    } catch(Throwable $e){}
    try { $db->exec("CREATE INDEX IF NOT EXISTS idx_ibof_username_lower ON ibof (lower(username))"); } catch(Throwable $e){}
    try { $db->exec("CREATE INDEX IF NOT EXISTS idx_ibof_macad_upper    ON ibof (upper(macad))");    } catch(Throwable $e){}
  } catch (Throwable $e) {
    echo "<div class='alert alert-danger m-2'>DB bootstrap warning: ".htmlspecialchars($e->getMessage())."</div>";
  }
}

/* -------- Reads for settings / lists -------- */
$resdns = $db->select($table_name_dns,'*','','') ?: [];

$advance = $db->select($table_name_advance,'*','id = :id','',[':id'=>1]) ?: [];
$per_pagexx = !empty($advance[0]['maxpg']) ? (int)$advance[0]['maxpg'] : 8;
$results_per_page = max(1,$per_pagexx);

// sort state
$db->insertIfEmpty($table_name_sort, ['sort'=>'def']);
$ressort = $db->select($table_name_sort,'*','','') ?: [];
$sortval = $ressort[0]['sort'] ?? 'def';

// row to edit
$resU = [];
if ($updateId) $resU = $db->select($table_name,'*','id = :id','',[':id'=>$updateId]) ?: [];

/* -------- Helpers that use DB -------- */
function dns_label($uuid){
  global $db;
  $uuid=(string)$uuid;
  if($uuid==='') return 'DNS missing';
  $ret=$db->select('dns','*','uid = :uid','',[':uid'=>$uuid]) ?: [];
  if(!$ret) return 'DNS missing ➤ '.htmlspecialchars($uuid);
  $title=htmlspecialchars($ret[0]['title']??''); $url=htmlspecialchars($ret[0]['url']??'');
  return ($title?:'DNS').' ➤ '.$url;
}
function toggle_mark_and_redirect($id,$page){
  global $db,$page_user;
  $row=$db->select('ibof','*','id = :id','',[':id'=>$id]) ?: [];
  if(!$row){ js_redirect($page_user.'?status=notfound'.($page>0?"&view=$page":'')); }
  $new=(int)($row[0]['mark']??0)?0:1;
  $db->update('ibof',['mark'=>$new],'id = :id',[':id'=>$id]);
  js_redirect($page_user.'?status=ok'.($page>0?"&view=$page":''));
}

/* ========================= Actions ========================= */
// CREATE
if (isset($_POST['submit'])) {
  unset($_POST['submit']);
  $allowed=['plid','name','uuid','macad','username','password','protec','cdate','udate','mark'];
  $ins=array_intersect_key($_POST,array_flip($allowed));
  if(empty($ins['plid']))  $ins['plid']=new_plid();
  if(empty($ins['cdate'])) $ins['cdate']=now_iso();
  if(empty($ins['udate'])) $ins['udate']=now_iso();
  if(!isset($ins['protec'])) $ins['protec']='1';
  if(!isset($ins['mark']))   $ins['mark']='0';
  $db->insert($table_name,$ins);
  js_redirect($page_user.'?status=ok');
}
// UPDATE
if (isset($_POST['submitU'])) {
  if(!$updateId || empty($resU)) js_redirect($page_user.'?status=notfound'.$selected_page);
  unset($_POST['submitU']);
  $allowed=['plid','name','uuid','macad','username','password','protec','mark'];
  $upd=array_intersect_key($_POST,array_flip($allowed));
  $upd['udate']=now_iso();
  $db->update($table_name,$upd,'id = :id',[':id'=>$updateId]);
  js_redirect($page_user.'?status=ok'.$selected_page);
}
// SAVE SORT
if (isset($_POST['submitS'])) {
  unset($_POST['submitS']);
  $db->update($table_name_sort,['sort'=>$_POST['sort']??'def'],'id = :id',[':id'=>1]);
  js_redirect($page_user.'?status=ok');
}
// DELETE single
if ($deleteId) { $db->delete($table_name,'id = :id',[':id'=>$deleteId]); js_redirect($page_user.'?status=ok'); }
// MARK toggle
if ($markId) { toggle_mark_and_redirect($markId,$currunt_page); }
// BULK DELETE (no IN(); delete row-by-row so we don't need query())
if (isset($_POST['bulk_delete']) && !empty($_POST['ids']) && is_array($_POST['ids'])) {
  foreach ($_POST['ids'] as $rid) {
    $rid = (int)$rid; if ($rid>0) $db->delete($table_name,'id = :id',[':id'=>$rid]);
  }
  $back = $page_user.'?status=ok'.($currunt_page?"&view=$currunt_page":'').($searchParam?:'').($showDups?'&dups=1':'');
  js_redirect($back);
}

/* ================= Search + Sort + Pagination ================ */
$placeholders=[]; $searchQuery='';
if($searchTerm!==''){ $searchQuery="(macad LIKE :q OR name LIKE :q OR username LIKE :q)"; $placeholders[':q']="%$searchTerm%"; }

$sortOrder='name ASC';
switch($sortval){
  case 'ZtoA': $sortOrder='name DESC'; break;
  case 'Mark_F': $sortOrder='mark DESC'; break;
  case 'UNMark_F': $sortOrder='mark ASC'; break;
  case 'new_F': $sortOrder='cdate DESC'; break;
  case 'old_F': $sortOrder='cdate ASC'; break;
  case 'newu_F': $sortOrder='udate DESC'; break;
  case 'oldu_F': $sortOrder='udate ASC'; break;
}

$countResult = $db->selectWithCount($table_name,"id",$searchQuery,$placeholders) ?: [['total'=>0]];
$totaleview  = (int)($countResult[0]['total'] ?? 0);
$total_pages = max(1,(int)ceil($totaleview / max(1,$results_per_page)));
$page        = max(1,min($currunt_page,$total_pages));
$start_from  = ($page-1)*$results_per_page;

$res = $db->select($table_name,'*',$searchQuery,"$sortOrder LIMIT $start_from, $results_per_page",$placeholders) ?: [];

/* ================= Duplicate summary (global) =================
   Wrapper-safe fallback: count in PHP (case-insensitive for username,
   uppercase for MAC). No raw GROUP BY needed.
================================================================ */
$dupUsernames=[]; $dupMacs=[];
if ($showDups && $searchTerm==='') {
  $allForDup = $db->select($table_name,'username, macad','','') ?: [];
  $uCount=[]; $mCount=[];
  foreach ($allForDup as $r) {
    $u = isset($r['username']) ? mb_strtolower(trim((string)$r['username'])) : '';
    $m = isset($r['macad'])    ? mb_strtoupper(trim((string)$r['macad']))    : '';
    if ($u!=='') $uCount[$u] = ($uCount[$u]??0)+1;
    if ($m!=='') $mCount[$m] = ($mCount[$m]??0)+1;
  }
  foreach ($uCount as $k=>$v) if ($v>1) $dupUsernames[$k]=$v;
  foreach ($mCount as $k=>$v) if ($v>1) $dupMacs[$k]=$v;
}

/* ---------------------------------------------------------------
   Duplicate details (wrapper-only methods; no prepared statements)
---------------------------------------------------------------- */
$dupDetailRows = [];
if ($dupType && $dupKey !== '') {
    // Normalizers that work even if mbstring isn't installed
    $toLower = function($s){ return function_exists('mb_strtolower') ? mb_strtolower((string)$s) : strtolower((string)$s); };
    $toUpper = function($s){ return function_exists('mb_strtoupper') ? mb_strtoupper((string)$s) : strtoupper((string)$s); };

    try {
        // Read minimal columns once; filter in PHP
        $all = $db->select(
            $table_name,
            'id, plid, name, uuid, macad, username, password, protec, cdate, udate, mark',
            '',
            ''
        ) ?: [];

        if ($dupType === 'mac') {
            $key = $toUpper($dupKey);
            foreach ($all as $r) {
                if ($toUpper($r['macad'] ?? '') === $key) $dupDetailRows[] = $r;
            }
        } else { // username
            $key = $toLower($dupKey);
            foreach ($all as $r) {
                if ($toLower($r['username'] ?? '') === $key) $dupDetailRows[] = $r;
            }
        }

        // Sort newest first to match the rest of the UI
        usort($dupDetailRows, function($a,$b){ return ($b['id']??0) <=> ($a['id']??0); });
    } catch (Throwable $e) {
        echo "<div class='container-fluid pt-2 px-4'><div class='row g-4'><div class='col-12'>".
             "<div class='bg-secondary rounded h-100 p-4'><div class='alert alert-danger mb-0'>".
             "Duplicate view error: ".htmlspecialchars($e->getMessage()).
             "</div></div></div></div></div>";
        $dupDetailRows = [];
    }
}
?>

<?php if (isset($_GET['create'])): ?>
<!-- =========================== CREATE =========================== -->
<div class="container-fluid pt-4 px-4"><div class="row g-4"><div class="col-12">
<div class="bg-secondary rounded h-100 p-4">
  <h2 class="mb-4">Add New User</h2>
  <form method="post">
    <input type="hidden" name="plid" value="<?= new_plid(); ?>">
    <div class="mb-3"><label class="form-label">Playlist Name</label>
      <input type="text" name="name" class="form-control" placeholder="Playlist Name">
    </div>
    <div class="mb-3"><label class="form-label">DNS</label>
      <?php $default_dns=$selected_uid; ?>
      <select class="form-select mb-3" id="uuid" name="uuid">
        <?php foreach ($resdns as $title): ?>
          <option value="<?= htmlspecialchars($title['uid']); ?>" <?= ($title['uid']==$default_dns)?'selected':''; ?>>
            <?= htmlspecialchars($title['title']); ?> ➤ <?= htmlspecialchars($title['url']); ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="mb-3"><label class="form-label">MAC Address</label>
      <input type="text" name="macad" id="mac_address" value="<?= htmlspecialchars($get_macaddress); ?>" class="form-control" placeholder="MAC Address">
    </div>
    <div class="mb-3"><label class="form-label">Username</label>
      <input type="text" name="username" class="form-control" placeholder="Username">
    </div>
    <div class="mb-3"><label class="form-label">Password</label>
      <input type="text" name="password" class="form-control" placeholder="Password">
    </div>
    <div class="mb-3"><label class="form-label">is Protected</label>
      <select class="form-select mb-3" id="protec" name="protec"><option value="1" selected>Yes</option><option value="0">No</option></select>
    </div>
    <div class="row"><div class="col-md-6 mb-3"><label class="form-label">Date added</label>
      <input type="text" name="cdate" class="form-control" value="<?= now_iso(); ?>" readonly></div>
      <div class="col-md-6 mb-3"><label class="form-label">Updated date</label>
      <input type="text" name="udate" class="form-control" value="<?= now_iso(); ?>" readonly></div>
    </div>
    <input type="hidden" name="mark" value="0">
    <button type="submit" name="submit" class="btn btn-primary">Save</button>
  </form>
</div></div></div></div>

<?php elseif ($updateId && !empty($resU)): ?>
<!-- ============================ EDIT ============================ -->
<div class="container-fluid pt-4 px-4"><div class="row g-4"><div class="col-12">
<div class="bg-secondary rounded h-100 p-4">
  <h2 class="mb-4">Edit User</h2>
  <form method="post">
    <input type="hidden" name="plid" value="<?= htmlspecialchars($resU[0]['plid']??''); ?>">
    <div class="mb-3"><label class="form-label">Playlist Name</label>
      <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($resU[0]['name']??''); ?>" placeholder="Playlist Name">
    </div>
    <div class="mb-3"><label class="form-label">DNS</label>
      <?php $selected_dns=$resU[0]['uuid'] ?? $selected_uid; ?>
      <select class="form-select mb-3" id="uuid" name="uuid">
        <?php foreach ($resdns as $title): ?>
          <option value="<?= htmlspecialchars($title['uid']); ?>" <?= ($title['uid']==$selected_dns)?'selected':''; ?>>
            <?= htmlspecialchars($title['title']); ?> ➤ <?= htmlspecialchars($title['url']); ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="mb-3"><label class="form-label">MAC Address</label>
      <input type="text" name="macad" id="mac_address" class="form-control" value="<?= htmlspecialchars($resU[0]['macad']??''); ?>" placeholder="MAC Address">
    </div>
    <div class="mb-3"><label class="form-label">Username</label>
      <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($resU[0]['username']??''); ?>" placeholder="Username">
    </div>
    <div class="mb-3"><label class="form-label">Password</label>
      <input type="text" name="password" class="form-control" value="<?= htmlspecialchars($resU[0]['password']??''); ?>" placeholder="Password">
    </div>
    <div class="mb-3"><label class="form-label">is Protected</label>
      <?php $protecc=(string)($resU[0]['protec']??'1'); ?>
      <select class="form-select mb-3" id="protec" name="protec">
        <option value="1" <?= $protecc==='1'?'selected':''; ?>>Yes</option>
        <option value="0" <?= $protecc==='0'?'selected':''; ?>>No</option>
      </select>
    </div>
    <div class="row"><div class="col-md-6 mb-3"><label class="form-label">Date added</label>
      <input type="text" name="cdate" class="form-control" value="<?= htmlspecialchars($resU[0]['cdate']??''); ?>" readonly></div>
      <div class="col-md-6 mb-3"><label class="form-label">Updated date</label>
      <input type="text" name="udate" class="form-control" value="<?= now_iso(); ?>" readonly></div>
    </div>
    <input type="hidden" name="mark" value="<?= htmlspecialchars((string)($resU[0]['mark']??'0')); ?>">
    <button type="submit" name="submitU" class="btn btn-primary">Update</button>
  </form>
</div></div></div></div>

<?php elseif ($dupType && $dupKey!==''): ?>
<!-- ===================== DUPLICATE DETAILS ===================== -->
<div class="container-fluid pt-2 px-4"><div class="row g-4"><div class="col-12">
<div class="bg-secondary rounded h-100 p-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Duplicate Details — <?= $dupType==='mac'?'MAC':'Username'; ?>: <code><?= htmlspecialchars($dupKey) ?></code></h4>
    <a class="btn btn-sm btn-outline-light" href="<?= $page_user ?>?dups=1<?= $selected_page ?><?= $searchParam ?>">Back to summary</a>
  </div>

  <?php if (empty($dupDetailRows)): ?>
    <div class="alert alert-info mb-0">No rows found for this value.</div>
  <?php else: ?>
    <form method="post" onsubmit="return confirm('Delete selected rows? This cannot be undone.');">
      <input type="hidden" name="bulk_delete" value="1">
      <div class="table-responsive">
        <table class="table">
          <thead><tr>
            <th style="width:40px;"><input type="checkbox" id="checkAllRows"></th>
            <th>#</th><th>Playlist</th><th>DNS</th><th>MAC</th><th>Username</th>
            <th>Password</th><th>Protected</th><th>Created</th><th>Updated</th><th>Mark</th>
          </tr></thead>
          <tbody>
            <?php foreach ($dupDetailRows as $r): ?>
            <tr>
              <td><input type="checkbox" name="ids[]" class="rowCheck" value="<?= (int)$r['id'] ?>"></td>
              <td><?= (int)$r['id'] ?></td>
              <td><?= htmlspecialchars((string)$r['name']) ?></td>
              <td><?= dns_label($r['uuid']) ?></td>
              <td><?= htmlspecialchars((string)$r['macad']) ?></td>
              <td><?= htmlspecialchars((string)$r['username']) ?></td>
              <td><?= htmlspecialchars((string)$r['password']) ?></td>
              <td><?= htmlspecialchars((string)$r['protec']) ?></td>
              <td><?= htmlspecialchars((string)$r['cdate']) ?></td>
              <td><?= htmlspecialchars((string)$r['udate']) ?></td>
              <td><?= htmlspecialchars((string)$r['mark']) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="d-flex justify-content-between align-items-center mt-3">
        <div><small class="text-muted">Tip: Use the header checkbox to select/unselect all.</small></div>
        <button type="submit" class="btn btn-danger">Delete Selected</button>
      </div>
    </form>
    <script>
      (function(){var all=document.getElementById('checkAllRows'); if(!all)return;
        var boxes=document.querySelectorAll('.rowCheck');
        all.addEventListener('change',function(){boxes.forEach(function(cb){cb.checked=all.checked;});});
      })();
    </script>
  <?php endif; ?>
</div></div></div></div>

<?php else: ?>
<!-- ============== SEARCH / SORT + DUP SUMMARY + TABLE ============== -->
<div class="container-fluid pt-4 px-4"><div class="row g-4"><div class="col-12">
  <div class="bg-secondary rounded h-100 p-4">
    <h6 class="mb-4">Search User</h6>
    <div class="d-flex align-items-center gap-2">
      <form method="get" class="mb-0 flex-grow-1">
        <div class="input-group w-100">
          <input type="text" name="search" class="form-control" value="<?= htmlspecialchars($searchTerm); ?>" placeholder="Search by Username, MAC or Playlist Name">
          <button type="submit" class="btn btn-primary">Search</button>
        </div>
      </form>
      <div class="nav-item dropdown">
        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
          <img class="rounded-circle me-lg-2" src="img/sort.png" alt="" style="width:40px;height:40px;">
        </a>
        <div class="dropdown-menu dropdown-menu-end bg-secondary border-0 rounded-0 rounded-bottom m-0">
          <?php
            $sorts=['def'=>'Default','AtoZ'=>'A to Z','ZtoA'=>'Z to A','Mark_F'=>'Marked First','UNMark_F'=>'Unmarked First','new_F'=>'Newest First','old_F'=>'Oldest First','newu_F'=>'Newest Updated First','oldu_F'=>'Oldest Updated First'];
            foreach($sorts as $val=>$label): ?>
            <form method="post" class="mb-0"><input type="hidden" name="sort" value="<?= $val ?>">
              <button type="submit" name="submitS" class="dropdown-item" style="color:red;"><?= $label ?></button>
            </form>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</div></div></div>

<?php if ($showDups): ?>
<div class="container-fluid pt-2 px-4"><div class="row g-4">
  <div class="col-md-6"><div class="bg-secondary rounded h-100 p-4">
    <h5 class="mb-3">Duplicate Usernames (All)</h5>
    <div class="table-responsive"><table class="table">
      <thead><tr><th>Username</th><th>Count</th></tr></thead><tbody>
      <?php if(!$dupUsernames): ?>
        <tr><td colspan="2"><em>No duplicates found.</em></td></tr>
      <?php else: foreach($dupUsernames as $u=>$cnt): ?>
        <tr>
          <td><a href="<?= $page_user ?>?dups=1&dup_type=user&dup_key=<?= urlencode($u) ?><?= $selected_page ?><?= $searchParam ?>"><?= htmlspecialchars($u) ?></a></td>
          <td><?= (int)$cnt ?></td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody></table></div>
  </div></div>

  <div class="col-md-6"><div class="bg-secondary rounded h-100 p-4">
    <h5 class="mb-3">Duplicate MACs (All)</h5>
    <div class="table-responsive"><table class="table">
      <thead><tr><th>MAC</th><th>Count</th></tr></thead><tbody>
      <?php if(!$dupMacs): ?>
        <tr><td colspan="2"><em>No duplicates found.</em></td></tr>
      <?php else: foreach($dupMacs as $m=>$cnt): ?>
        <tr>
          <td><a href="<?= $page_user ?>?dups=1&dup_type=mac&dup_key=<?= urlencode($m) ?><?= $selected_page ?><?= $searchParam ?>"><?= htmlspecialchars($m) ?></a></td>
          <td><?= (int)$cnt ?></td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody></table></div>
  </div></div>
</div></div>
<?php else: ?>
<div class="container-fluid pt-2 px-4"><div class="row g-4"><div class="col-12">
  <div class="bg-secondary rounded h-100 p-3 d-flex justify-content-between align-items-center">
    <span>Click to show duplicate summary (global) for MAC & Username.</span>
    <a class="btn btn-sm btn-outline-warning" href="<?= $page_user ?>?dups=1<?= $selected_page ?><?= $searchParam ?>">Show Duplicates</a>
  </div>
</div></div></div>
<?php endif; ?>

<div class="container-fluid pt-4 px-4"><div class="row g-4"><div class="col-12">
  <div class="bg-secondary rounded h-100 p-4">
    <h2 class="mb-4">Current User</h2>
    <div class="text-end"><a type="button" href="./<?= $page_user ?>?create" class="btn btn-square btn-primary m-2"><i class="fa fa-plus"></i></a></div>
    <div class="table-responsive"><table class="table">
      <thead><tr>
        <th>#</th><th>Playlist Name</th><th>DNS</th><th>Mac Address</th><th>Username</th>
        <th>is Protected</th><th>Mac Settings</th><th>Edit</th><th>Delete</th><th>Mark</th>
      </tr></thead>
      <tbody>
        <?php foreach($res as $row):
          $uKey = mb_strtolower(trim((string)($row['username']??'')));
          $mKey = mb_strtoupper(trim((string)($row['macad']??'')));
          $isDupU = $uKey!=='' && isset($dupUsernames[$uKey]);
          $isDupM = $mKey!=='' && isset($dupMacs[$mKey]);
        ?>
        <tr>
          <td><?= htmlspecialchars((string)$row['id']); ?></td>
          <td><?= htmlspecialchars((string)$row['name']); ?></td>
          <td><?= dns_label($row['uuid']); ?></td>
          <td>
            <a href="<?= $page_user ?>?dups=1&dup_type=mac&dup_key=<?= urlencode((string)$row['macad']) ?><?= $selected_page ?><?= $searchParam ?>"><?= htmlspecialchars((string)$row['macad']); ?></a>
            <?php if($isDupM): ?><span class="badge-dup ms-2">dup</span><?php endif; ?>
          </td>
          <td>
            <a href="<?= $page_user ?>?dups=1&dup_type=user&dup_key=<?= urlencode((string)$row['username']) ?><?= $selected_page ?><?= $searchParam ?>"><?= htmlspecialchars((string)$row['username']); ?></a>
            <?php if($isDupU): ?><span class="badge-dup ms-2">dup</span><?php endif; ?>
          </td>
          <td><?= htmlspecialchars((string)$row['protec']); ?></td>
          <td><a class="btn btn-square btn-warning m-2" href="<?= $pagemac; ?>?create&mac=<?= urlencode((string)$row['macad']); ?>&name=<?= urlencode((string)$row['name']); ?>"><i class="fa fa-id-card"></i></a></td>
          <td><a class="btn btn-square btn-success m-2" href="<?= $page_user; ?>?update=<?= (int)$row['id']; ?>&uuid=<?= urlencode((string)$row['uuid']); ?><?= $selected_page; ?>"><i class="fa fa-pencil-square-o"></i></a></td>
          <td><a class="btn btn-square btn-primary m-2" href="#" data-href="<?= $page_user; ?>?delete=<?= (int)$row['id']; ?>" data-bs-toggle="modal" data-bs-target="#confirm-delete"><i class="fa fa-trash"></i></a></td>
          <td><a class="btn btn-square <?= ((int)$row['mark']===1?'btn-warning':'btn-outline-warning'); ?> m-2" href="<?= $page_user; ?>?mark=<?= (int)$row['id']; ?><?= $selected_page; ?>"><i class="fa fa-star"></i></a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table></div>
  </div>
</div></div></div>

<!-- Pagination -->
<div class="container-fluid pt-4 px-4"><div class="row g-4"><div class="col-12">
  <div class="bg-secondary rounded h-100 p-4">
    <?php
      $is_mobile = !empty($_SERVER['HTTP_USER_AGENT']) && preg_match('/(android|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i', $_SERVER['HTTP_USER_AGENT']);
      $max_window = $is_mobile ? 3 : 5;
      $window_start = max(1, $page - (int)floor($max_window/2));
      $window_end   = min($total_pages, $window_start + $max_window - 1);
      if ($window_end - $window_start + 1 < $max_window) $window_start = max(1, $window_end - $max_window + 1);
    ?>
    <?php if ($results_per_page < $totaleview): ?>
    <div class="pagination"><div class="btn-toolbar" role="toolbar"><div class="btn-group me-2" role="group">
      <?php if($page>1): ?><a class="btn btn-primary" href="<?= $page_user ?>?view=<?= $page-1 ?><?= $searchParam ?><?= $showDups?'&dups=1':'' ?>"><?= $is_mobile?'&lt;':'Previous' ?></a><?php endif; ?>
      <?php if($window_start>1): ?><a class="btn btn-primary" href="<?= $page_user ?>?view=1<?= $searchParam ?><?= $showDups?'&dups=1':'' ?>">1</a><?php if($window_start>2) echo "..."; endif; ?>
      <?php for($i=$window_start;$i<=$window_end;$i++): ?>
        <a class="btn <?= ($i==$page?'btn-warning':'btn-primary'); ?>" href="<?= $page_user ?>?view=<?= $i ?><?= $searchParam ?><?= $showDups?'&dups=1':'' ?>"><?= $i ?></a>
      <?php endfor; ?>
      <?php if($window_end<$total_pages): ?><?php if($window_end<$total_pages-1) echo "..."; ?><a class="btn btn-primary" href="<?= $page_user ?>?view=<?= $total_pages ?><?= $searchParam ?><?= $showDups?'&dups=1':'' ?>"><?= $total_pages ?></a><?php endif; ?>
      <?php if($page<$total_pages): ?><a class="btn btn-primary" href="<?= $page_user ?>?view=<?= $page+1 ?><?= $searchParam ?><?= $showDups?'&dups=1':'' ?>"><?= $is_mobile?'&gt;':'Next' ?></a><?php endif; ?>
    </div></div></div>
    <?php endif; ?>
  </div>
</div></div></div>

<?php endif; /* end modes */ ?>

<?php include('includes/footer.php'); ?>
</body>
</html>
