<?php
// payments_manage.php (fixed sidebar overlap + fully responsive)
declare(strict_types=1);
session_start();
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/config.php'; // must define $conn as PDO

if (!isset($conn) || !($conn instanceof PDO)) {
  http_response_code(500);
  echo "DB not connected. Ensure config.php sets \$conn as a PDO instance.";
  exit;
}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* ---------------------------
   CONFIG
---------------------------- */
$UPLOAD_DIR = __DIR__ . '/uploads/payments/';
$UPLOAD_URL = 'uploads/payments/';
$ALLOWED_IMAGE_MIME = ['image/png','image/jpeg','image/jpg','image/webp'];
$MAX_IMAGE_BYTES = 3 * 1024 * 1024;

/* ---------------------------
   HELPERS
---------------------------- */
function h(?string $s): string { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
function ensure_upload_dir(string $dir): void {
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  if (!is_dir($dir) || !is_writable($dir)) {
    http_response_code(500);
    echo "Upload directory not writable: " . h($dir);
    exit;
  }
}
ensure_upload_dir($UPLOAD_DIR);

// CSRF
if (empty($_SESSION['csrf_payments'])) {
  $_SESSION['csrf_payments'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_payments'];

/* ---------------------------
   IMAGE UPLOAD
---------------------------- */
function handle_image_upload(array $file, string $UPLOAD_DIR, array $ALLOWED_IMAGE_MIME, int $MAX_IMAGE_BYTES): array {
  if (empty($file['name'])) return ['ok'=>true, 'filename'=>null]; // no upload
  if (!empty($file['error']) && $file['error'] !== UPLOAD_ERR_OK) return ['ok'=>false, 'error'=>'Upload error code '.$file['error']];
  if ($file['size'] > $MAX_IMAGE_BYTES) return ['ok'=>false, 'error'=>'Image too large (max 3MB).'];
  $finfo = @finfo_open(FILEINFO_MIME_TYPE);
  $mime  = $finfo ? finfo_file($finfo, $file['tmp_name']) : null;
  if ($finfo) finfo_close($finfo);
  if (!$mime || !in_array($mime, $ALLOWED_IMAGE_MIME, true)) return ['ok'=>false, 'error'=>'Invalid image type. Allowed: PNG, JPG, WEBP'];
  $ext = ['image/png'=>'.png','image/jpeg'=>'.jpg','image/jpg'=>'.jpg','image/webp'=>'.webp'][$mime] ?? '.bin';
  $name = bin2hex(random_bytes(8)).$ext;
  $dest = rtrim($UPLOAD_DIR,'/').'/'.$name;
  if (!move_uploaded_file($file['tmp_name'], $dest)) return ['ok'=>false, 'error'=>'Failed to move uploaded file.'];
  return ['ok'=>true, 'filename'=>$name];
}

/* ---------------------------
   ROUTING + ACTIONS
---------------------------- */
$mode = $_GET['mode'] ?? 'list';
$id   = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$flash = ['type'=>null,'msg'=>null];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $posted_csrf = $_POST['csrf'] ?? '';
  if (!hash_equals($csrf, $posted_csrf)) {
    $flash = ['type'=>'error','msg'=>'Invalid CSRF token. Please reload the page.'];
  } else {
    if (($_POST['action'] ?? '') === 'create' || ($_POST['action'] ?? '') === 'update') {
      $payload = [
        ':payment_mode'       => trim($_POST['payment_mode'] ?? ''),
        ':bank_name'          => trim($_POST['bank_name'] ?? ''),
        ':account_holdername' => trim($_POST['account_holdername'] ?? ''),
        ':account_detail'     => trim($_POST['account_detail'] ?? ''),
        ':account_type'       => trim($_POST['account_type'] ?? ''),
        ':bank_codename1'     => trim($_POST['bank_codename1'] ?? ''),
        ':bank_codename2'     => trim($_POST['bank_codename2'] ?? ''),
        ':bank_ifsc_code'     => trim($_POST['bank_ifsc_code'] ?? ''),
        ':bank_iban_code'     => trim($_POST['bank_iban_code'] ?? ''),
        ':bitcoin_number'     => trim($_POST['bitcoin_number'] ?? ''),
        ':bitcoin_address'    => trim($_POST['bitcoin_address'] ?? ''),
        ':agent_location'     => trim($_POST['agent_location'] ?? ''),
        ':agent_address'      => trim($_POST['agent_address'] ?? ''),
      ];
      if ($payload[':payment_mode'] === '') {
        $flash = ['type'=>'error','msg'=>'Payment mode is required.'];
      } else {
        $newImageFile = null;
        if (isset($_FILES['image'])) {
          $up = handle_image_upload($_FILES['image'], $UPLOAD_DIR, $ALLOWED_IMAGE_MIME, $MAX_IMAGE_BYTES);
          if (!$up['ok']) $flash = ['type'=>'error','msg'=>$up['error']]; else $newImageFile = $up['filename'];
        }
        if ($flash['type'] === null) {
          if (($_POST['action'] ?? '') === 'create') {
            $sql = "INSERT INTO available_payment
              (payment_mode, bank_name, account_holdername, account_detail, image, account_type,
               bank_codename1, bank_codename2, bank_ifsc_code, bank_iban_code,
               bitcoin_number, bitcoin_address, agent_location, agent_address)
              VALUES
              (:payment_mode,:bank_name,:account_holdername,:account_detail,:image,:account_type,
               :bank_codename1,:bank_codename2,:bank_ifsc_code,:bank_iban_code,
               :bitcoin_number,:bitcoin_address,:agent_location,:agent_address)";
            $stmt = $conn->prepare($sql);
            $payload[':image'] = $newImageFile;
            $stmt->execute($payload);
            $flash = ['type'=>'success','msg'=>'Payment method added.'];
            $mode = 'list';
          } else { // update
            $editId = (int)($_POST['id'] ?? 0);
            $old = $conn->prepare("SELECT image FROM available_payment WHERE id = :id");
            $old->execute([':id'=>$editId]);
            $oldRow = $old->fetch(PDO::FETCH_ASSOC);

            $imgSet = ''; $params = $payload;
            if ($newImageFile !== null) { $imgSet = ', image = :image'; $params[':image'] = $newImageFile; }

            $sql = "UPDATE available_payment SET
                      payment_mode = :payment_mode,
                      bank_name = :bank_name,
                      account_holdername = :account_holdername,
                      account_detail = :account_detail,
                      account_type = :account_type,
                      bank_codename1 = :bank_codename1,
                      bank_codename2 = :bank_codename2,
                      bank_ifsc_code = :bank_ifsc_code,
                      bank_iban_code = :bank_iban_code,
                      bitcoin_number = :bitcoin_number,
                      bitcoin_address = :bitcoin_address,
                      agent_location = :agent_location,
                      agent_address = :agent_address
                      $imgSet
                    WHERE id = :id";
            $params[':id'] = $editId;
            $stmt = $conn->prepare($sql);
            $stmt->execute($params);
            if ($newImageFile !== null && !empty($oldRow['image'])) @unlink($UPLOAD_DIR.$oldRow['image']);
            $flash = ['type'=>'success','msg'=>'Payment method updated.'];
            $mode = 'list';
          }
        }
      }
    }
    if (($mode === 'delete') && $id > 0) {
      $old = $conn->prepare("SELECT image FROM available_payment WHERE id = :id");
      $old->execute([':id'=>$id]);
      $row = $old->fetch(PDO::FETCH_ASSOC);
      $del = $conn->prepare("DELETE FROM available_payment WHERE id = :id");
      $del->execute([':id'=>$id]);
      if ($row && !empty($row['image'])) @unlink($UPLOAD_DIR.$row['image']);
      $flash = ['type'=>'success','msg'=>'Payment method deleted.'];
      $mode = 'list';
    }
  }
}

/* ---------------------------
   FETCH ROW FOR EDIT
---------------------------- */
$edit = null;
if ($mode === 'edit' && $id > 0) {
  $stmt = $conn->prepare("SELECT * FROM available_payment WHERE id = :id");
  $stmt->execute([':id'=>$id]);
  $edit = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$edit) $mode = 'list';
}

/* ---------------------------
   LISTING (search + pagination)
---------------------------- */
$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset = ($page - 1) * $perPage;

$where = []; $params = [];
if ($q !== '') {
  $where[] = "(payment_mode LIKE :q OR bank_name LIKE :q OR account_holdername LIKE :q OR account_type LIKE :q OR agent_location LIKE :q)";
  $params[':q'] = "%$q%";
}
$whereSql = $where ? ('WHERE '.implode(' AND ', $where)) : '';

$sqlCount = "SELECT COUNT(*) FROM available_payment $whereSql";
$st = $conn->prepare($sqlCount); $st->execute($params);
$totalRows = (int)$st->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));

$sqlList = "SELECT * FROM available_payment $whereSql ORDER BY id DESC LIMIT :lim OFFSET :off";
$st = $conn->prepare($sqlList);
foreach ($params as $k=>$v) $st->bindValue($k, $v);
$st->bindValue(':lim', $perPage, PDO::PARAM_INT);
$st->bindValue(':off', $offset, PDO::PARAM_INT);
$st->execute();
$listRows = $st->fetchAll(PDO::FETCH_ASSOC);

function qlink(array $add = []): string {
  $b = $_GET;
  foreach ($add as $k=>$v) { if ($v === null) unset($b[$k]); else $b[$k] = $v; }
  return '?' . http_build_query($b);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/>
  <title>Available Payments — Manage</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <style>
    /* Theme */
    .btn-orange { background:#ff7a00; }
    .btn-orange:hover { background:#e46f00; }
    .chip { background:rgba(255,122,0,0.08); color:#b45500; }
    .ring-orange:focus { box-shadow:0 0 0 3px rgba(255,122,0,0.35); outline:none; }

    /* Sticky headers only on md+ */
    @media (min-width: 768px) { .table-sticky thead th { position: sticky; top: 0; background:#fff; z-index:1; } }

    /* TRUE mobile cards for tables */
    @media (max-width: 767.98px) {
      .responsive-table table { border: 0; }
      .responsive-table thead { display: none; }
      .responsive-table tr { display: block; margin: 0.75rem 0; border: 1px solid #f3f4f6; border-radius: 0.75rem; overflow: hidden; }
      .responsive-table td { display: grid; grid-template-columns: 40% 1fr; gap: .5rem; text-align: left; padding: .6rem .9rem; border-bottom: 1px solid #f9fafb; }
      .responsive-table td:last-child { border-bottom: 0; }
      .responsive-table td::before {
        content: attr(data-label);
        font-weight: 600;
        color: #374151;
      }
      .act-stack { display: flex; flex-direction: column; gap: .5rem; }
      .img-cell img { width: 64px; height: 64px; object-fit: cover; border-radius: .5rem; }
    }/* Hide scrollbars but keep scrolling */
.no-scrollbar::-webkit-scrollbar { width: 0; height: 0; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

/* (Optional) Hide the window’s scrollbars as well */
html, body { -ms-overflow-style: none; scrollbar-width: none; }
html::-webkit-scrollbar, body::-webkit-scrollbar { display: none; }

  </style>
</head>
<body class="bg-gray-50 overflow-x-hidden">
  <?php include 'header.php'; ?>

  <div class="flex min-h-screen">
    <?php include 'side_bar.php'; ?>

    <!-- IMPORTANT: use padding-left (pl-64), not margin-left, and allow shrink (min-w-0) -->
    <main class="flex-1 min-w-0 relative p-3 sm:p-4 md:p-8 md:pl-64">
      <!-- Header -->
      <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-4 sm:px-6 md:px-8 py-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <div>
            <h1 class="text-xl sm:text-2xl md:text-3xl font-bold text-gray-900">Available Payments</h1>
            <p class="text-sm sm:text-base text-gray-600">Create, view, update, and delete payment methods.</p>
          </div>
          <div class="flex items-center gap-2">
            <a href="<?= h(qlink(['mode'=>'add','id'=>null])) ?>" class="btn-orange text-white font-semibold px-4 py-2 rounded-xl shadow hover:shadow-md transition text-sm w-full sm:w-auto text-center">+ Add Payment</a>
            <span class="chip px-3 py-1 rounded-full text-xs sm:text-sm border border-orange-200">Orange • White</span>
          </div>
        </div>

        <?php if ($flash['type']): ?>
          <div class="px-4 sm:px-6 md:px-8 py-3 text-sm <?= $flash['type']==='success' ? 'bg-green-50 text-green-800 border-t border-green-200' : 'bg-red-50 text-red-800 border-t border-red-200' ?>">
            <?= $flash['msg'] ?>
          </div>
        <?php endif; ?>
      </div>

      <!-- ADD / EDIT FORM -->
      <?php if ($mode === 'add' || $mode === 'edit'): ?>
        <?php $row = $edit ?: []; ?>
        <form action="" method="POST" enctype="multipart/form-data" class="mt-4 bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <?php if ($mode === 'edit'): ?>
            <input type="hidden" name="action" value="update"><input type="hidden" name="id" value="<?= (int)$id ?>">
          <?php else: ?>
            <input type="hidden" name="action" value="create">
          <?php endif; ?>

          <div class="px-4 sm:px-6 md:px-8 py-3 border-b border-gray-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
            <div class="font-semibold text-gray-900"><?= $mode==='add' ? 'Add New Payment' : 'Edit Payment #'.(int)$id ?></div>
            <a class="text-sm px-3 py-2 rounded-xl border border-gray-200 hover:border-gray-300 text-center" href="<?= h(qlink(['mode'=>'list','id'=>null])) ?>">Back to list</a>
          </div>

          <div class="p-4 sm:p-6 md:p-8 grid grid-cols-1 gap-6">
            <!-- Row 1 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-1">Payment Mode *</label>
                <input name="payment_mode" required value="<?= h($row['payment_mode'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Bank Name</label>
                <input name="bank_name" value="<?= h($row['bank_name'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Account Holder Name</label>
                <input name="account_holdername" value="<?= h($row['account_holdername'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
            </div>

            <!-- Row 2 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-1">Account Detail</label>
                <input name="account_detail" value="<?= h($row['account_detail'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Account Type</label>
                <input name="account_type" value="<?= h($row['account_type'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Image (PNG/JPG/WEBP, ≤3MB)</label>
                <input type="file" name="image" accept="image/png,image/jpeg,image/jpg,image/webp" class="w-full">
                <?php if (!empty($row['image'])): ?>
                  <div class="mt-2 text-xs text-gray-600">Current: <a class="text-orange-600 underline" href="<?= h($UPLOAD_URL.$row['image']) ?>" target="_blank">view</a></div>
                <?php endif; ?>
              </div>
            </div>

            <!-- Row 3 -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-1">Bank Codename 1</label>
                <input name="bank_codename1" value="<?= h($row['bank_codename1'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Bank Codename 2</label>
                <input name="bank_codename2" value="<?= h($row['bank_codename2'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">IFSC Code</label>
                <input name="bank_ifsc_code" value="<?= h($row['bank_ifsc_code'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">IBAN Code</label>
                <input name="bank_iban_code" value="<?= h($row['bank_iban_code'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
            </div>

            <!-- Row 4 -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-1">Bitcoin Number</label>
                <input name="bitcoin_number" value="<?= h($row['bitcoin_number'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div class="md:col-span-2">
                <label class="block text-sm text-gray-700 mb-1">Bitcoin Address</label>
                <input name="bitcoin_address" value="<?= h($row['bitcoin_address'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
              <div>
                <label class="block text-sm text-gray-700 mb-1">Agent Location</label>
                <input name="agent_location" value="<?= h($row['agent_location'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
            </div>

            <!-- Row 5 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm text-gray-700 mb-1">Agent Address</label>
                <input name="agent_address" value="<?= h($row['agent_address'] ?? '') ?>" class="w-full px-3 py-2 border border-gray-300 rounded-xl ring-orange">
              </div>
            </div>

            <div class="flex flex-col sm:flex-row justify-end gap-2">
              <a href="<?= h(qlink(['mode'=>'list','id'=>null])) ?>" class="px-4 py-2 rounded-xl border border-gray-200 hover:border-gray-300 text-center">Cancel</a>
              <button class="btn-orange text-white font-semibold px-5 py-2 rounded-xl shadow hover:shadow-md transition"><?= $mode==='add' ? 'Create' : 'Update' ?></button>
            </div>
          </div>
        </form>
      <?php endif; ?>

      <!-- LIST -->
      <?php if ($mode === 'list'): ?>
        <!-- Filters -->
        <form class="mt-4 bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-4 sm:px-6 md:px-8 py-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
            <div class="text-sm text-gray-700">
              Total <span class="font-semibold"><?= number_format($totalRows) ?></span> payment method(s).
            </div>
            <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
              <input name="q" value="<?= h($q) ?>" placeholder="Search mode/bank/holder/type…" class="px-3 py-2 w-full sm:w-64 max-w-full border border-gray-300 rounded-xl ring-orange text-sm">
              <div class="flex gap-2">
                <button class="btn-orange text-white px-4 py-2 rounded-xl shadow hover:shadow-md text-sm w-full sm:w-auto">Search</button>
                <a href="<?= h(qlink(['q'=>null,'page'=>null])) ?>" class="px-4 py-2 rounded-xl border border-gray-200 hover:border-gray-300 text-sm bg-white w-full sm:w-auto text-center">Reset</a>
              </div>
            </div>
          </div>
        </form>

        <div class="mt-3 bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden responsive-table">
          <div class="overflow-x-auto">
            <table class="min-w-full table-auto table-sticky text-xs sm:text-sm">
              <thead>
                <tr class="text-left text-gray-700 border-b border-gray-100"><th></th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">#</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Payment Mode</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Bank</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Holder</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Account Detail</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Type</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Codes</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">BTC</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Agent</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Image</th>
                  <th class="px-3 sm:px-4 py-2 sm:py-3 font-semibold">Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php if ($listRows): $i=$offset+1; foreach ($listRows as $r): ?>
                  <tr class="border-b border-gray-50 hover:bg-orange-50"><td></td>
                    <!-- data-labels for mobile cards -->
                    <td class="px-3 sm:px-4 py-2 text-gray-500" data-label="#"> <?= $i++ ?> </td>
                    <td class="px-3 sm:px-4 py-2 font-medium text-gray-900" data-label="Payment Mode"><?= h($r['payment_mode']) ?></td>
                    <td class="px-3 sm:px-4 py-2" data-label="Bank"><?= h($r['bank_name']) ?></td>
                    <td class="px-3 sm:px-4 py-2" data-label="Holder"><?= h($r['account_holdername']) ?></td>
                    <td class="px-3 sm:px-4 py-2 break-words" data-label="Account Detail"><?= h($r['account_detail']) ?></td>
                    <td class="px-3 sm:px-4 py-2" data-label="Type"><?= h($r['account_type']) ?></td>
                    <td class="px-3 sm:px-4 py-2" data-label="Codes">
                      <div class="text-gray-700">
                        <div><span class="text-gray-500">C1:</span> <?= h($r['bank_codename1']) ?></div>
                        <div><span class="text-gray-500">C2:</span> <?= h($r['bank_codename2']) ?></div>
                        <div><span class="text-gray-500">IFSC:</span> <?= h($r['bank_ifsc_code']) ?></div>
                        <div><span class="text-gray-500">IBAN:</span> <?= h($r['bank_iban_code']) ?></div>
                      </div>
                    </td>
                    <td class="px-3 sm:px-4 py-2 break-words" data-label="BTC">
                      <div class="text-gray-700">
                        <div><span class="text-gray-500">No:</span> <?= h($r['bitcoin_number']) ?></div>
                        <div><span class="text-gray-500">Addr:</span> <?= h($r['bitcoin_address']) ?></div>
                      </div>
                    </td>
                    <td class="px-3 sm:px-4 py-2 break-words" data-label="Agent">
                      <div class="text-gray-700">
                        <div><?= h($r['agent_location']) ?></div>
                        <div><?= h($r['agent_address']) ?></div>
                        <div class="text-xs text-gray-500 mt-1"><?= h($r['register_date']) ?></div>
                      </div>
                    </td>
                    <td class="px-3 sm:px-4 py-2 img-cell" data-label="Image">
                      <?php if (!empty($r['image'])): ?>
                        <a href="<?= h($UPLOAD_URL.$r['image']) ?>" target="_blank">
                          <img src="<?= h($UPLOAD_URL.$r['image']) ?>" alt="" class="w-14 h-14 object-cover rounded-lg border border-orange-100" />
                        </a>
                      <?php else: ?>
                        <span class="text-gray-400">—</span>
                      <?php endif; ?>
                    </td>
                    <td class="px-3 sm:px-4 py-2" data-label="Actions">
                      <div class="flex flex-wrap gap-2 act-stack">
                        <a class="px-3 py-1.5 text-sm rounded-lg border border-gray-200 hover:border-gray-300 bg-white text-center" href="<?= h(qlink(['mode'=>'edit','id'=>$r['id']])) ?>">Edit</a>
                        <form action="<?= h(qlink(['mode'=>'delete','id'=>$r['id']])) ?>" method="POST" onsubmit="return confirm('Delete this payment method?');" class="contents sm:inline">
                          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                          <button class="px-3 py-1.5 text-sm rounded-lg border border-red-200 text-red-700 hover:border-red-300 bg-white w-full sm:w-auto">Delete</button>
                        </form>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; else: ?>
                  <tr><td class="px-4 py-8 text-center text-gray-500" colspan="11">No payment methods found.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <!-- Pagination -->
          <div class="px-4 sm:px-6 md:px-8 py-3 border-t border-gray-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 text-sm">
            <div>Page <span class="font-semibold"><?= $page ?></span> of <span class="font-semibold"><?= $totalPages ?></span></div>
            <div class="flex flex-wrap gap-2">
              <a class="px-3 py-2 rounded-xl border <?= $page<=1 ? 'opacity-50 pointer-events-none' : 'hover:border-gray-300' ?>" href="<?= h(qlink(['page'=>1])) ?>">First</a>
              <a class="px-3 py-2 rounded-xl border <?= $page<=1 ? 'opacity-50 pointer-events-none' : 'hover:border-gray-300' ?>" href="<?= h(qlink(['page'=>max(1,$page-1)])) ?>">Prev</a>
              <a class="px-3 py-2 rounded-xl border <?= $page>=$totalPages ? 'opacity-50 pointer-events-none' : 'hover:border-gray-300' ?>" href="<?= h(qlink(['page'=>min($totalPages,$page+1)])) ?>">Next</a>
              <a class="px-3 py-2 rounded-xl border <?= $page>=$totalPages ? 'opacity-50 pointer-events-none' : 'hover:border-gray-300' ?>" href="<?= h(qlink(['page'=>$totalPages])) ?>">Last</a>
            </div>
          </div>
        </div>
      <?php endif; ?>

      <div class="h-20"></div>
    </main>

    <?php include 'footer.php'; ?>
  </div>
</body>
</html>
