<?php


/* Debug (disable in production) */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';   // defines $conn = new PDO(...)
require_once __DIR__ . '/auth_guard.php';

function flash($msg='', $type='info'){
  if ($msg !== '') $_SESSION['_flash'] = ['msg'=>$msg, 'type'=>$type];
  $f = $_SESSION['_flash'] ?? null; unset($_SESSION['_flash']); return $f;
}

/* ---------- Handle UPDATE (Edit modal submits here) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_ib'])) {
  $id      = (int)($_POST['indexId'] ?? 0);
  $name    = trim($_POST['name'] ?? '');
  $email   = trim($_POST['email'] ?? '');
  $number  = trim($_POST['number'] ?? '');
  $country = trim($_POST['country'] ?? '');
  $status  = (int)($_POST['status'] ?? 0);

  if ($id <= 0 || $name === '' || $email === '') {
    flash('Name and Email are required.', 'error');
    header('Location: '.$_SERVER['REQUEST_URI']); exit;
  }

  $sqlU = "UPDATE ib1
           SET name = :name, email = :email, number = :number,
               country = :country, status = :status
           WHERE indexId = :id";
  $stmtU = $conn->prepare($sqlU);
  $ok = $stmtU->execute([
    ':name'    => $name,
    ':email'   => $email,
    ':number'  => $number,
    ':country' => $country,
    ':status'  => $status,
    ':id'      => $id,
  ]);

  if ($ok) flash('IB user updated successfully.','success');
  else     flash('Update failed.','error');

  header('Location: '.$_SERVER['REQUEST_URI']); exit;
}

/* ---------- Inputs / Filter ---------- */
$st = isset($_GET['st']) ? (int)$_GET['st'] : -1;

/* ---------- Fetch rows ---------- */
$where = '';
$params = [];
if ($st === 0 || $st === 1) { $where = 'WHERE status = :st'; $params[':st'] = $st; }

$sql = "
  SELECT
    indexId, name, email, number, country,
    ib_ref_code, noClients, reg_date, status
  FROM ib1
  $where
  ORDER BY reg_date DESC, indexId DESC
  LIMIT 500
";
$stmt = $conn->prepare($sql);
foreach ($params as $k=>$v) $stmt->bindValue($k, $v, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ---------- Flash (if any) ---------- */
$flash = flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>IB User List</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.min.css" rel="stylesheet"/>
  <style>
    .btn-sm{padding:.25rem .5rem;font-size:.75rem;line-height:1rem;border-radius:.375rem}
    .table-wrap{max-height:70vh;overflow:auto}
    .table-wrap thead th{position:sticky;top:0;z-index:1}
    .actions{display:flex;flex-wrap:wrap;gap:.25rem;justify-content:center}
    .modal{display:none}
    .modal.show{display:block}
  </style>
</head>
<body class="bg-gray-100">
<?php include "header.php"; ?>

<div class="min-h-screen md:pl-64">
  <?php include "side_bar.php"; ?>

  <main class="px-4 sm:px-6 py-6">
    <!-- Topbar -->
    <div class="flex items-center justify-between bg-white border border-gray-200 shadow-sm rounded-xl px-3 sm:px-4 py-2 mb-4">
      <h1 class="text-lg sm:text-xl font-semibold text-gray-800">IB User List</h1>
      <form method="get" class="hidden sm:flex items-center gap-2">
        <label class="text-sm text-gray-600">Status</label>
        <select name="st" class="border border-gray-300 rounded-md text-sm px-2 py-1">
          <?php
            $opts = [-1=>'All', 1=>'Active', 0=>'Inactive'];
            foreach ($opts as $k=>$v) {
              $sel = ($k===$st) ? 'selected' : '';
              echo "<option value=\"$k\" $sel>$v</option>";
            }
          ?>
        </select>
        <button class="btn-sm bg-[#CD7F32] text-white hover:brightness-95">Apply</button>
      </form>
    </div>

    <?php if ($flash): ?>
      <div class="mb-4 rounded-md p-3 text-sm
        <?= $flash['type']==='success' ? 'bg-green-50 text-green-700 border border-green-200' :
           ($flash['type']==='error'   ? 'bg-rose-50 text-rose-700 border border-rose-200' :
                                         'bg-blue-50 text-blue-700 border border-blue-200') ?>">
        <?= e($flash['msg']) ?>
      </div>
    <?php endif; ?>

    <div class="bg-white border border-gray-200 shadow-sm rounded-xl p-3 sm:p-4">
      <div class="flex items-center justify-between mb-3">
        <div>
          <h2 class="text-base sm:text-lg font-semibold text-gray-800">Introducing Brokers</h2>
          <p class="text-xs text-gray-500 mt-0.5">Showing <?= count($rows) ?> record(s)</p>
        </div>
      </div>

      <div class="table-wrap rounded-lg border border-gray-200">
        <table class="min-w-full bg-white">
          <thead class="bg-[#CD7F32] text-white text-xs sm:text-sm">
            <tr>
              <th class="p-2 sm:p-3 text-left">Name</th>
              <th class="p-2 sm:p-3 text-left">Email</th>
              <th class="p-2 sm:p-3 text-left">Registered</th>
              <th class="p-2 sm:p-3 text-center">Status</th>
              <th class="p-2 sm:p-3 text-center">Action</th>
            </tr>
          </thead>
          <tbody class="text-xs sm:text-sm">
            <?php if (!count($rows)): ?>
              <tr>
                <td colspan="10" class="p-6 text-center text-gray-500">No IB users found.</td>
              </tr>
            <?php else:
              $base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on' ? 'https':'http') . '://' . $_SERVER['HTTP_HOST'];
              foreach ($rows as $r):
                $id   = (int)$r['indexId'];
                $name = $r['name'] ?? '';
                $email= $r['email'] ?? '';
                $code = $r['ib_ref_code'] ?? 'noCode';
                $reg  = $r['reg_date'] ?? '';
                $status = (int)($r['status'] ?? 0);
                $refLink = $base . '/signup.php?ref=' . urlencode($code);
            ?>
              <tr class="border-b border-gray-100 hover:bg-gray-50">
                <td class="p-2 sm:p-3 align-middle">
                  <span class="text-gray-900"><?= e($name) ?></span>
                  <div class="text-[11px] text-gray-500 mt-0.5">Ref: <?= e($code) ?></div>
                </td>
                <td class="p-2 sm:p-3 align-middle">
                  <a class="text-blue-600 hover:underline" href="mailto:<?= e($email) ?>"><?= e($email) ?></a>
                </td>
                <td class="p-2 sm:p-3 align-middle">
                  <span class="whitespace-nowrap"><?= e($reg) ?></span>
                </td>
                <td class="p-2 sm:p-3 align-middle text-center">
                  <?php if ($status === 1): ?>
                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-emerald-700 bg-emerald-50 border border-emerald-200">Active</span>
                  <?php else: ?>
                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-amber-700 bg-amber-50 border border-amber-200">Inactive</span>
                  <?php endif; ?>
                </td>
                <td class="p-2 sm:p-3 align-middle">
                  <div class="actions">
                    <!-- View (modal) -->
                    <button type="button"
                      class="btn-sm bg-gray-100 hover:bg-gray-200 border border-gray-300 text-gray-800"
                      data-open="#view_<?= $id ?>" title="View">
                      <i class="ri-eye-line"></i>
                    </button>

                    <!-- Edit (modal) -->
                    <button type="button"
                      class="btn-sm bg-[#CD7F32] text-white hover:brightness-95"
                      data-open="#edit_<?= $id ?>" title="Edit">
                      <i class="ri-edit-2-line"></i>
                    </button>

                    <!-- (optional) Delete (still posts to ib_delete.php) -->
                    <form method="post" action="ib_delete.php" onsubmit="return confirm('Delete this IB user?');" class="inline">
                      <input type="hidden" name="id" value="<?= $id ?>">
                      <button type="submit" class="btn-sm bg-red-600 text-white hover:bg-red-700" title="Delete">
                        <i class="ri-delete-bin-6-line"></i>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>

              <!-- View Modal -->
              <div id="view_<?= $id ?>" class="modal fixed inset-0 z-40 items-center justify-center" style="margin-top:30px;">
                <div class="fixed inset-0 bg-black/40" data-close="#view_<?= $id ?>"></div>
                <div class="relative z-50 mx-4 my-8 sm:mx-auto max-w-lg w-full">
                  <div class="bg-white rounded-xl shadow-xl border border-gray-200">
                    <div class="px-5 py-3 border-b">
                      <h3 class="font-semibold text-gray-800">IB Details</h3>
                    </div>
                    <div class="p-5 space-y-2 text-sm">
                      <div><span class="text-gray-500">Name:</span> <span class="font-medium"><?= e($name) ?></span></div>
                      <div><span class="text-gray-500">Email:</span> <a class="text-blue-600 hover:underline" href="mailto:<?= e($email) ?>"><?= e($email) ?></a></div>
                      <div><span class="text-gray-500">Number:</span> <span class="font-medium"><?= e($r['number'] ?? '') ?></span></div>
                      <div><span class="text-gray-500">Country:</span> <span class="font-medium"><?= e($r['country'] ?? '') ?></span></div>
                      <div><span class="text-gray-500">Ref Code:</span> <span class="font-mono"><?= e($code) ?></span></div>
                      <div class="flex items-center gap-2">
                        <span class="text-gray-500">Ref Link:</span>
                        <input class="w-full border rounded px-2 py-1 text-xs" value="<?= e($refLink) ?>" readonly />
                        <button class="btn-sm bg-gray-100 border" onclick="copyText('<?= e($refLink) ?>', this)"><i class="ri-file-copy-line"></i></button>
                      </div>
                      <div><span class="text-gray-500">Registered:</span> <span class="font-medium"><?= e($reg) ?></span></div>
                      <div><span class="text-gray-500">Status:</span>
                        <?php if ($status === 1): ?>
                          <span class="inline-flex items-center px-2 py-0.5 rounded-full text-emerald-700 bg-emerald-50 border border-emerald-200">Active</span>
                        <?php else: ?>
                          <span class="inline-flex items-center px-2 py-0.5 rounded-full text-amber-700 bg-amber-50 border border-amber-200">Inactive</span>
                        <?php endif; ?>
                      </div>
                    </div>
                    <div class="px-5 py-3 border-t flex justify-end gap-2">
                      <button class="btn-sm bg-gray-200 hover:bg-gray-300" data-close="#view_<?= $id ?>">Close</button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Edit Modal -->
              <div id="edit_<?= $id ?>" class="modal fixed inset-0 z-40 items-center justify-center" style="margin-top:30px;">
                <div class="fixed inset-0 bg-black/40" data-close="#edit_<?= $id ?>"></div>
                <div class="relative z-50 mx-4 my-8 sm:mx-auto max-w-lg w-full">
                  <div class="bg-white rounded-xl shadow-xl border border-gray-200">
                    <div class="px-5 py-3 border-b">
                      <h3 class="font-semibold text-gray-800">Edit IB</h3>
                    </div>
                    <form method="post" class="p-5 space-y-3">
                      <input type="hidden" name="update_ib" value="1">
                      <input type="hidden" name="indexId" value="<?= $id ?>">
                      <div>
                        <label class="block text-xs text-gray-600 mb-1">Name</label>
                        <input name="name" class="w-full border rounded px-3 py-2" value="<?= e($name) ?>" required>
                      </div>
                      <div>
                        <label class="block text-xs text-gray-600 mb-1">Email</label>
                        <input type="email" name="email" class="w-full border rounded px-3 py-2" value="<?= e($email) ?>" required>
                      </div>
                      <div>
                        <label class="block text-xs text-gray-600 mb-1">Number</label>
                        <input name="number" class="w-full border rounded px-3 py-2" value="<?= e($r['number'] ?? '') ?>">
                      </div>
                      <div>
                        <label class="block text-xs text-gray-600 mb-1">Country</label>
                        <input name="country" class="w-full border rounded px-3 py-2" value="<?= e($r['country'] ?? '') ?>">
                      </div>
                      <div>
                        <label class="block text-xs text-gray-600 mb-1">Status</label>
                        <select name="status" class="w-full border rounded px-3 py-2">
                          <option value="1" <?= $status===1?'selected':'' ?>>Active</option>
                          <option value="0" <?= $status===0?'selected':'' ?>>Inactive</option>
                        </select>
                      </div>
                      <div class="pt-2 flex justify-end gap-2 border-t">
                        <button type="button" class="btn-sm bg-gray-200 hover:bg-gray-300" data-close="#edit_<?= $id ?>">Cancel</button>
                        <button type="submit" class="btn-sm bg-[#CD7F32] text-white hover:brightness-95">Save</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>

            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </main>
</div>

<?php include "footer.php"; ?>

<script>
/* Clipboard helper */
function copyText(text, btn){
  navigator.clipboard.writeText(text).then(()=>{
    const old = btn.innerHTML;
    btn.innerHTML = '<i class="ri-check-line"></i>';
    setTimeout(()=> btn.innerHTML = old, 1200);
  });
}

/* Tiny modal controller (no external JS) */
function openModal(sel){ const el = document.querySelector(sel); if(!el) return;
  el.classList.add('show'); el.classList.add('flex'); el.classList.remove('hidden'); }
function closeModal(sel){ const el = document.querySelector(sel); if(!el) return;
  el.classList.remove('show'); el.classList.remove('flex'); el.classList.add('hidden'); }

document.addEventListener('click', (e)=>{
  const openSel = e.target.closest('[data-open]')?.getAttribute('data-open');
  if (openSel) { openModal(openSel); return; }
  const closeSel = e.target.closest('[data-close]')?.getAttribute('data-close');
  if (closeSel) { closeModal(closeSel); return; }
});
/* Ensure modals start hidden */
document.querySelectorAll('.modal').forEach(m=>m.classList.add('hidden'));
</script>
</body>
</html>
