<?php
session_start();
error_reporting(0);
include('config.php');
require_once('auth_guard.php');

// -----------------------
// Inputs
// -----------------------
$q = trim($_GET['q'] ?? '');
$records_per_page = 10;
$current_page = max(1, (int)($_GET['page'] ?? 1));

// -----------------------
// Shared WHERE + params
// -----------------------
$where = '';
$params = [];
if ($q !== '') {
  $where = "WHERE (t1.trade_id LIKE :q OR t1.email LIKE :q OR t2.ac_name LIKE :q OR t1.tradePlatform LIKE :q)";
  $params[':q'] = '%'.$q.'%';
}

// -----------------------
// Count
// -----------------------
$sqlCount = "SELECT COUNT(*)
             FROM liveaccount AS t1
             INNER JOIN account_types AS t2 ON t1.account_type = t2.ac_group
             $where";
$stmt = $conn->prepare($sqlCount);
if ($q !== '') $stmt->bindValue(':q', $params[':q'], PDO::PARAM_STR);
$stmt->execute();
$total_records = (int)$stmt->fetchColumn();

$total_pages  = max(1, (int)ceil($total_records / $records_per_page));
$current_page = min($current_page, $total_pages);
$offset = ($current_page - 1) * $records_per_page;

// -----------------------
// Range (define BEFORE HTML)
// -----------------------
$from = $total_records ? ($offset + 1) : 0;
$to   = min($offset + $records_per_page, $total_records);

// -----------------------
// Page data
// -----------------------
$sql = "SELECT t1.email AS email,t1.trader_pwd,t1.invester_pwd,
               t1.id AS id,
               t1.trade_id AS trade_id,
               t2.ac_name AS account_type,
               t1.tradePlatform AS tradePlatform,
               t1.Registered_Date AS Registered_Date
        FROM liveaccount AS t1
        INNER JOIN account_types AS t2 ON t1.account_type = t2.ac_group
        $where
        ORDER BY Registered_Date DESC
        LIMIT :offset, :limit";
$stmt = $conn->prepare($sql);
if ($q !== '') $stmt->bindValue(':q', $params[':q'], PDO::PARAM_STR);
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$stmt->bindValue(':limit',  (int)$records_per_page, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);

// -----------------------
// Helpers
// -----------------------
function mask_pwd(string $pwd): string {
  $len = strlen($pwd);
  return str_repeat('•', max(8, $len ?: 8));
}

function render_rows($rows){
  ob_start();
  if (!empty($rows)) {
    foreach ($rows as $r) {
      $tp = (string)($r->trader_pwd ?? '');
      $ip = (string)($r->invester_pwd ?? '');
      ?>
      <tr>
        <td><?= htmlentities($r->trade_id) ?></td>
        <td><?= htmlentities($r->email) ?></td>
        <td><?= htmlentities($r->account_type) ?></td>

        <!-- Trader Password (with eye) -->
        <td class="pwd-cell">
          <?php if ($tp !== ''): ?>
            <span class="pwd" data-pwd="<?= htmlspecialchars($tp, ENT_QUOTES) ?>" data-state="hidden">Trader
              <?= htmlspecialchars(mask_pwd($tp), ENT_QUOTES) ?>
            </span>
            <button type="button" class="eye-btn js-eye" aria-label="Show password" title="Show/Hide">
              <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7Zm0 12a5 5 0 1 1 0-10 5 5 0 0 1 0 10Z"/></svg>
            </button>
          <?php else: ?>
            <span class="muted">—</span>
          <?php endif; ?>
        </td>

        <!-- Investor Password (with eye) -->
        <td class="pwd-cell"><!-- FIXED class name -->
          <?php if ($ip !== ''): ?>
            <span class="pwd" data-pwd="<?= htmlspecialchars($ip, ENT_QUOTES) ?>" data-state="hidden">Invester
              <?= htmlspecialchars(mask_pwd($ip), ENT_QUOTES) ?>
            </span>
            <button type="button" class="eye-btn js-eye" aria-label="Show password" title="Show/Hide">
              <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7Zm0 12a5 5 0 1 1 0-10 5 5 0 0 1 0 10Z"/></svg>
            </button>
          <?php else: ?>
            <span class="muted">—</span>
          <?php endif; ?>
        </td>

        
        <td><?= htmlentities($r->Registered_Date) ?></td>
      </tr>
    <?php }
  } else { ?>
    <tr>
      <td colspan="7" style="text-align:center; color:#6b7280; padding:18px;">No accounts to display.</td>
    </tr>
  <?php }
  return ob_get_clean();
}

function page_link($page, $label, $isActive=false, $isDisabled=false){
  $classes = 'page-item';
  if ($isActive)   $classes .= ' active';
  if ($isDisabled) $classes .= ' disabled';
  $aria = htmlspecialchars((string)$label, ENT_QUOTES);
  echo '<li class="'.$classes.'"><a class="page-link js-page" href="#" data-page="'.(int)$page.'" aria-label="'.$aria.'">'.$label.'</a></li>';
}

function render_pagination($current_page, $total_pages){
  ob_start(); ?>
  <nav aria-label="Page navigation example">
    <ul class="pagination">
      <?php
      $window = 2;
      $start  = max(1, $current_page - $window);
      $end    = min($total_pages, $current_page + $window);

      page_link(1, '&laquo;&laquo; First', $current_page === 1, false);
      page_link(max(1,$current_page-1), '&laquo; Prev', $current_page === 1, false);

      if ($start > 1) {
        page_link(1, '1', $current_page === 1);
        if ($start > 2) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
      }
      for ($i=$start; $i<=$end; $i++) page_link($i, (string)$i, $i === $current_page);
      if ($end < $total_pages) {
        if ($end < $total_pages - 1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
        page_link($total_pages, (string)$total_pages, $current_page === $total_pages);
      }

      page_link(min($total_pages,$current_page+1), 'Next &raquo;', $current_page === $total_pages, false);
      page_link($total_pages, 'Last &raquo;&raquo;', $current_page === $total_pages, false);
      ?>
    </ul>
  </nav>
  <?php
  return ob_get_clean();
}

// -----------------------
// AJAX endpoint
// -----------------------
if (isset($_GET['ajax']) && $_GET['ajax'] === 'list') {
  $resp = [
    'tbody'      => render_rows($results),
    'pagination' => render_pagination($current_page, $total_pages),
    'meta'       => [
      'from'  => $from,
      'to'    => $to,
      'total' => $total_records,
    ],
  ];
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($resp);
  exit;
}
?>
<style>
  /* ====== LAYOUT & THEME ====== */
  @media (min-width:768px){ main.md\:ml-64{ margin-left:16rem!important; } }

  /* Narrower page width (decreased from 1200px) */
  .dashboard-content-one{ max-width:980px; margin-inline:auto; width:100%; padding:18px 14px 32px; }

  .dashboard-summery-one .row.align-items-center{ display:flex; align-items:center; justify-content:space-between; gap:.75rem; }
  .dashboard-summery-one .col-6:first-child{ flex:1 1 auto; }
  .dashboard-summery-one .col-6:last-child{ flex:0 0 auto; text-align:right; }
  @media (max-width:575.98px){
    .dashboard-summery-one .row.align-items-center{ flex-direction:column; align-items:stretch; }
    .dashboard-summery-one .col-6:last-child{ text-align:left; }
  }
  .table{ table-layout:auto; border-collapse:separate; border-spacing:0; width:100%; }
  .table thead th, .table tbody td{ text-align:left; border-right:1px solid var(--vm-border)!important; white-space:nowrap; }
  .table thead th:last-child, .table tbody td:last-child{ border-right:0!important; }
  nav[aria-label="Page navigation example"] .pagination{ justify-content:center; flex-wrap:wrap; }
  .flex.h-screen{ min-height:100vh; height:auto; }
  .row.gutters-20{ margin-left:0; margin-right:0; }
  .row.gutters-20 > [class*="col-"]{ padding-left:0; padding-right:0; }
  .btn-fill-lmd{ line-height:1; }

  .pagination{ gap:.5rem; margin-top:16px; justify-content:center; flex-wrap:wrap; }
  .page-item{ display:inline-flex; }
  .page-item .page-link{
    min-width:36px; height:36px; display:inline-flex; align-items:center; justify-content:center;
    padding:0 .7rem; border-radius:10px!important; border:1px solid var(--vm-border);
    background:var(--vm-white); color:var(--vm-text); font-weight:600; line-height:1;
    transition:all .18s ease; text-decoration:none;
  }
  .page-item .page-link:hover{ border-color:var(--vm-orange); color:var(--vm-orange); box-shadow:0 6px 14px rgba(255,122,26,.15); transform:translateY(-1px); }
  .page-item.active .page-link{ background:linear-gradient(135deg,var(--vm-orange),var(--vm-orange-600)); border-color:transparent; color:#fff; box-shadow:0 6px 14px rgba(232,101,0,.25); }
  .page-item.disabled .page-link{ opacity:.5; pointer-events:none; background:#fafafa; color:#9ca3af; }

  :root{
    --vm-bg:#f6f7fb; --vm-white:#fff; --vm-text:#1f2937; --vm-muted:#6b7280;
    --vm-orange:#ff7a1a; --vm-orange-600:#e86500; --vm-orange-100:#fff3e8;
    --vm-border:#e5e7eb; --vm-shadow:0 8px 24px rgba(0,0,0,.07);
  }
  body.bg-gray-100{ background:var(--vm-bg)!important; color:var(--vm-text); }
  .card{ border:0!important; border-radius:18px!important; background:var(--vm-white); box-shadow:var(--vm-shadow); overflow:hidden; }
  .card-body{ padding:16px!important; } @media (min-width:768px){ .card-body{ padding:20px!important; } }
  .dashboard-summery-one{ background:var(--vm-white); border:1px solid var(--vm-border); box-shadow:var(--vm-shadow); border-radius:16px; padding:10px 14px; }
  .btn-fill-lmd{ display:inline-flex; align-items:center; gap:.5rem; padding:.55rem .9rem; border-radius:9999px; border:0; font-weight:600; letter-spacing:.2px; text-decoration:none!important; transition:all .18s ease; }
  .radius-30{ border-radius:30px!important; }
  .text-light{ color:#fff!important; }
  .bg-dark-pastel-green,.shadow-dark-pastel-green{ background:linear-gradient(135deg,var(--vm-orange),var(--vm-orange-600))!important; box-shadow:0 8px 20px rgba(232,101,0,.25)!important; }
  .bg-orange-peel,.shadow-dodger-blue{ background:var(--vm-white)!important; color:var(--vm-orange)!important; border:2px solid var(--vm-orange)!important; box-shadow:0 8px 20px rgba(255,122,26,.18)!important; }
  .bg-orange-peel:hover{ background:var(--vm-orange)!important; color:#fff!important; }
  .bg-dark-pastel-green:hover{ filter:brightness(.96); transform:translateY(-1px); }
  .table{ margin:0; border-color:var(--vm-border)!important; }
  .table > :not(caption) > * > *{ padding:10px 12px; vertical-align:middle; background-color:transparent; }
  .table thead tr th{ background:linear-gradient(180deg,var(--vm-orange),var(--vm-orange-600)); color:#fff; font-weight:700; border:0!important; position:sticky; top:0; z-index:2; }
  .table tbody tr{ background:var(--vm-white); border-bottom:1px solid var(--vm-border); }
  .table tbody tr:nth-child(even){ background:#fffdfb; }
  .table tbody tr:hover{ background:var(--vm-orange-100); }
  .table td small,.table td .muted{ color:var(--vm-muted); }
  .table-responsive{ border:1px solid var(--vm-border); border-radius:14px; overflow:hidden; box-shadow:var(--vm-shadow); }

  /* Header / search area */
  .search-wrap{ display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; margin:8px 0 4px; }
  .search-input{
    flex:1 1 240px; border:1px solid var(--vm-border); border-radius:12px; padding:.5rem .8rem;
    background:#fff; color:var(--vm-text); outline:none; font-size:.95rem;
  }
  .search-input:focus{ border-color:var(--vm-orange); box-shadow:0 0 0 3px rgba(255,122,26,.15); }
  .search-meta{ color:var(--vm-muted); font-size:.9rem; margin-bottom:10px; }

  /* Password eye button */
  .pwd-cell{ display:flex; align-items:center; gap:.4rem; }
  .eye-btn{
    border:0; background:#fff; width:26px; height:26px; display:inline-flex; align-items:center; justify-content:center;
    border-radius:50%; cursor:pointer; transition:background .18s ease, transform .18s ease; border:1px solid var(--vm-border);
  }
  .eye-btn:hover{ background:#fff7ef; transform:translateY(-1px); border-color:#ffd3b3; }
  .eye-btn svg{ display:block; }
  .fade-enter{ opacity:.35; }
</style>

<body class="bg-gray-100">
<?php include('header.php');?>

<div class="flex flex-col md:flex-row h-screen">
  <?php include "side_bar.php";?>

  <main class="flex-1 p-4 md:p-6 md:ml-64">
    <div class="dashboard-content-one">
      <div class="row gutters-20">
        <div class="col-xl-10 col-sm-12 col-12">
          <div class="dashboard-summery-one mg-b-20">
            <div class="row align-items-center">
              <div class="col-6">
                <button type="button" class="btn-fill-lmd radius-30 text-light shadow-dark-pastel-green bg-dark-pastel-green">
                  Total Client Live Account
                </button>
              </div>
              <div class="col-6">
                <div class="item-content">
                  <a href="dashboard.php" class="btn-fill-lmd radius-30 text-light shadow-dodger-blue bg-orange-peel">Get Back</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Live Search -->
      <div class="search-wrap">
        <input id="liveSearch" type="text"
               value="<?= htmlspecialchars($q, ENT_QUOTES) ?>"
               placeholder="Search by Account No, Email, Account Type, or Platform..."
               class="search-input" autocomplete="off" />
        <?php if ($q !== ''): ?>
          <a href="?" class="reset-btn" style="border-radius:12px;border:1px solid var(--vm-border);background:#fff;color:var(--vm-text);padding:.5rem .8rem;font-weight:600;text-decoration:none;">Reset</a>
        <?php endif; ?>
      </div>

      <div id="searchMeta" class="search-meta">
        <?php
          echo ($q !== '')
            ? 'Showing results for “'.htmlspecialchars($q, ENT_QUOTES).'”. '
            : '';
          echo $total_records
            ? 'Showing <strong>'.(int)$from.'&ndash;'.(int)$to.'</strong> of <strong>'.(int)$total_records.'</strong>.'
            : 'No records found.';
        ?>
      </div>

      <div class="row" style="padding-top:10px;">
        <div class="col-lg-12 grid-margin stretch-card">
          <div class="card">
            <div class="card-body">
              <div class="table-responsive pt-3" id="tableWrap">
                <table class="table table-bordered">
                  <thead>
                    <tr>
                      <th>Account No</th>
                      <th>Client Email</th>
                      <th>Account Type</th>
                      <th>Trader/Invester Password</th>

                      <th>Reg Date</th>
                    </tr>
                  </thead>
                  <tbody id="tbody">
                    <?= render_rows($results) ?>
                  </tbody>
                </table>
              </div>

              <div id="paginationWrap">
                <?= render_pagination($current_page, $total_pages) ?>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>

<?php include('footer.php'); ?>

<script>
// Debounce helper
const debounce = (fn, ms=300) => { let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a), ms); }; };

const input          = document.getElementById('liveSearch');
const tbody          = document.getElementById('tbody');
const paginationWrap = document.getElementById('paginationWrap');
const meta           = document.getElementById('searchMeta');
const tableWrap      = document.getElementById('tableWrap');

function maskPwd(s){ const n = Math.max(8, (s||'').length); return '•'.repeat(n); }
function eyeSVG(shown){
  return shown
    ? '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3l18 18-1.5 1.5L18 19.5C16.3 20.5 14.3 21 12 21 7 21 3 16.5 2 14c.5-1.2 1.8-3.1 3.7-4.9L1.5 4.5 3 3Zm7 7.2l3.8 3.8c.1-.3.2-.6.2-1 0-2.2-1.8-4-4-4-.3 0-.7.1-1 .2Zm-2.3-2.3l1.7 1.7c.5-.2 1-.3 1.6-.3 3.1 0 5.6 2.5 5.6 5.6 0 .6-.1 1.1-.3 1.6l1.7 1.7c2-1.6 3.5-3.5 4-4.7-1-2.5-5-7-10-7-1.8 0-3.4.4-4.8 1.1Z"/></svg>'
    : '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7Zm0 12a5 5 0 1 1 0-10 5 5 0 0 1 0 10Z"/></svg>';
}

// Toggle reveal/hide passwords for BOTH cells (event delegation)
document.addEventListener('click', (ev) => {
  const btn = ev.target.closest('.js-eye');
  if (!btn) return;

  const cell = btn.closest('.pwd-cell');
  const span = cell ? cell.querySelector('.pwd') : null;
  if (!span) return;

  const state = span.getAttribute('data-state') || 'hidden';
  const raw = span.getAttribute('data-pwd') || '';

  if (state === 'hidden') {
    span.textContent = raw;
    span.setAttribute('data-state', 'shown');
    btn.setAttribute('aria-label', 'Hide password');
    btn.innerHTML = eyeSVG(true);
  } else {
    span.textContent = maskPwd(raw);
    span.setAttribute('data-state', 'hidden');
    btn.setAttribute('aria-label', 'Show password');
    btn.innerHTML = eyeSVG(false);
  }
});

// AJAX list loader
async function loadList(page = 1){
  const q = input.value.trim();
  tableWrap.classList.add('fade-enter');  // subtle loading state
  try {
    const url = new URL(window.location.href);
    url.searchParams.set('ajax', 'list');
    url.searchParams.set('page', page);
    url.searchParams.set('q', q);
    const res  = await fetch(url.toString(), { credentials:'same-origin' });
    const data = await res.json();

    tbody.innerHTML          = data.tbody || '';
    paginationWrap.innerHTML = data.pagination || '';

    const from  = data?.meta?.from ?? 0;
    const to    = data?.meta?.to ?? 0;
    const total = data?.meta?.total ?? 0;
    meta.innerHTML = (q ? `Showing results for “${escapeHtml(q)}”. ` : '') +
                     (total ? `Showing <strong>${from}&ndash;${to}</strong> of <strong>${total}</strong>.` : 'No records found.');

    bindPagination(); // re-bind page links
  } catch (e) {
    console.error(e);
  } finally {
    tableWrap.classList.remove('fade-enter');
  }
}

function bindPagination(){
  paginationWrap.querySelectorAll('a.js-page').forEach(a => {
    a.addEventListener('click', (ev) => {
      ev.preventDefault();
      const p = parseInt(a.dataset.page || '1', 10);
      if (!isNaN(p)) loadList(p);
    }, { once:true });
  });
}

function escapeHtml(s){
  const div = document.createElement('div');
  div.innerText = s;
  return div.innerHTML;
}

// Live search on typing
const debouncedLoad = debounce(() => loadList(1), 250);
input.addEventListener('input', debouncedLoad);

// First bind for initial HTML
bindPagination();
</script>
