<?php
// accounts_list.php — smooth UI, grouped by category, copy creds, buyer link

session_start();
if (!isset($_SESSION['admin'])) { header('Location: index.php'); exit; }

require __DIR__ . '/../db.php';
$config = require __DIR__ . '/../config.php';

$msg = '';
$err = '';

// --- DELETE / FORCE DELETE ---
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE account_id = ?");
        $stmt->execute([$id]);
        $cnt = (int)$stmt->fetchColumn();

        if ($cnt > 0 && (!isset($_GET['confirm']) || $_GET['confirm'] !== 'yes')) {
            $err = "⛔ Can't delete: {$cnt} order(s) reference this account. Use Force Delete to remove orders + account.";
        } else {
            // grab image path first
            $stmt = $pdo->prepare("SELECT image_path FROM accounts WHERE id = ?");
            $stmt->execute([$id]);
            $r = $stmt->fetch(PDO::FETCH_ASSOC);

            // delete orders if any
            if ($cnt > 0) {
                $delOrders = $pdo->prepare("DELETE FROM orders WHERE account_id = ?");
                $delOrders->execute([$id]);
            }
            // delete account
            $delAcc = $pdo->prepare("DELETE FROM accounts WHERE id = ?");
            $delAcc->execute([$id]);

            // delete image file
            if ($r && !empty($r['image_path'])) {
                @unlink(__DIR__ . '/../uploads/' . $r['image_path']);
            }

            $msg = "✅ Account deleted." . ($cnt > 0 ? " (Also removed {$cnt} related order(s))." : "");
            header('Location: accounts_list.php');
            exit;
        }
    } catch (PDOException $e) {
        $err = "❌ DB Error: " . $e->getMessage();
    }
}

// --- FETCH ACCOUNTS ---
try {
    $rows = $pdo->query(
        "SELECT a.*,
                c.id    AS cat_id,
                c.title AS category_title,
                c.slug  AS category_slug
         FROM accounts a
         LEFT JOIN categories c ON a.category_id = c.id
         ORDER BY COALESCE(c.sort_order,9999),
                  COALESCE(c.title,''),
                  a.created_at DESC"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $rows = [];
    $err = "❌ DB Error fetching accounts: " . $e->getMessage();
}

// group by category title
$groups = [];
foreach ($rows as $r) {
    $cat = $r['category_title'] ? $r['category_title'] : 'Uncategorized';
    if (!isset($groups[$cat])) $groups[$cat] = [];
    $groups[$cat][] = $r;
}

// latest buyer helper
function getLatestBuyer($pdo, $account_id) {
    try {
        $stmt = $pdo->prepare(
            "SELECT u.username, u.telegram_id
             FROM orders o
             JOIN users u ON o.user_id = u.id
             WHERE o.account_id = ? AND o.status = 'paid'
             ORDER BY o.created_at DESC
             LIMIT 1"
        );
        $stmt->execute([$account_id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return false;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Accounts — Admin</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<style>
  :root{
    --bg:#050510;
    --card:#101018;
    --card-soft:#161623;
    --accent:#6c5ce7;
    --accent-soft:#a29bfe;
    --danger:#ff7675;
    --text-main:#ffffff;
    --text-muted:#a4a7b3;
    --border-soft:rgba(255,255,255,0.08);
  }
  *{box-sizing:border-box}
  body{
    margin:0;
    font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
    background:radial-gradient(circle at top,#1b1b33 0,#050510 55%);
    color:var(--text-main);
    -webkit-font-smoothing:antialiased;
  }
  .shell{
    max-width:980px;
    margin:0 auto;
    padding:18px 14px 40px;
  }

  .top-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:16px;
  }
  .title-wrap h1{
    margin:0;
    font-size:22px;
    letter-spacing:.02em;
  }
  .subtitle{
    margin-top:4px;
    font-size:13px;
    color:var(--text-muted);
  }
  .nav-pill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:4px;
    border-radius:999px;
    background:rgba(0,0,0,0.55);
    backdrop-filter:blur(12px);
  }
  .nav-pill a{
    text-decoration:none;
    padding:8px 14px;
    border-radius:999px;
    font-size:13px;
    font-weight:600;
    display:inline-flex;
    align-items:center;
    gap:6px;
    background:linear-gradient(135deg,#ffffff,#f3f1ff);
    color:#181820;
    box-shadow:0 6px 18px rgba(0,0,0,0.32);
    border:1px solid rgba(255,255,255,0.85);
    transition:transform .12s ease, box-shadow .12s ease;
  }
  .nav-pill a:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 26px rgba(0,0,0,0.4);
  }
  .nav-pill a:active{
    transform:translateY(0);
    box-shadow:0 3px 10px rgba(0,0,0,0.25);
  }

  .notice{
    padding:10px 12px;
    border-radius:10px;
    font-size:13px;
    margin-bottom:10px;
  }
  .notice.ok{
    background:rgba(46,213,115,0.14);
    border:1px solid rgba(46,213,115,0.6);
    color:#b7ffce;
  }
  .notice.err{
    background:rgba(255,71,87,0.14);
    border:1px solid rgba(255,71,87,0.7);
    color:#ffd4d8;
  }

  .category-card{
    background:var(--card);
    border-radius:16px;
    padding:14px 14px 10px;
    border:1px solid var(--border-soft);
    box-shadow:0 16px 40px rgba(0,0,0,0.55);
    margin-bottom:18px;
  }
  .cat-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:8px;
  }
  .cat-title{
    font-size:17px;
    font-weight:700;
  }
  .cat-meta{
    font-size:12px;
    color:var(--text-muted);
  }

  .acct{
    display:flex;
    gap:12px;
    align-items:flex-start;
    padding:10px;
    border-radius:12px;
    background:var(--card-soft);
    border:1px solid rgba(255,255,255,0.06);
    margin-bottom:12px;
  }
  .acct-img{
    flex:0 0 160px;
    height:120px;
    border-radius:10px;
    overflow:hidden;
    background:#050510;
    display:flex;
    align-items:center;
    justify-content:center;
  }
  .acct-img img{
    width:100%;
    height:100%;
    object-fit:cover;
    display:block;
  }
  .acct-body{
    flex:1 1 auto;
    min-width:0;
  }

  .acct-title-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:4px;
  }
  .acct-title{
    font-size:15px;
    font-weight:650;
  }
  .badge-sold{
    padding:5px 10px;
    border-radius:999px;
    font-size:11px;
    font-weight:700;
    background:rgba(250,184,50,0.14);
    border:1px solid rgba(250,184,50,0.7);
    color:#ffd58b;
  }
  .badge-price{
    padding:5px 10px;
    border-radius:999px;
    font-size:11px;
    font-weight:700;
    background:rgba(255,255,255,0.06);
    border:1px solid rgba(255,255,255,0.16);
    color:#ffe3b0;
  }

  .caption-box{
    margin-top:4px;
    padding:8px 9px;
    border-radius:10px;
    background:rgba(0,0,0,0.35);
    border:1px solid rgba(255,255,255,0.06);
    font-size:13px;
    color:var(--text-muted);
    max-height:90px;
    overflow:auto;
    cursor:pointer;
  }
  .caption-box.expanded{max-height:none}
  .caption-box::-webkit-scrollbar{width:6px}
  .caption-box::-webkit-scrollbar-thumb{background:rgba(255,255,255,0.2);border-radius:6px}

  .meta-row{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    margin-top:6px;
    font-size:12px;
  }
  .meta-pill{
    padding:5px 8px;
    border-radius:999px;
    background:rgba(255,255,255,0.05);
    border:1px solid rgba(255,255,255,0.08);
    color:var(--text-muted);
  }

  .creds-row{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-top:8px;
  }
  .cred-pill{
    position:relative;
    flex:0 0 auto;
    min-width:150px;
    max-width:220px;
    padding:8px 10px;
    border-radius:10px;
    border:1px solid rgba(255,255,255,0.14);
    background:rgba(255,255,255,0.06);
    font-size:13px;
    display:flex;
    align-items:center;
    gap:8px;
    cursor:pointer;
  }
  .cred-icon{font-size:15px}
  .cred-value{
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    flex:1 1 auto;
  }
  .cred-overlay{
    position:absolute;
    inset:0;
    border-radius:10px;
    background:rgba(0,0,0,0.7);
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:12px;
    opacity:0;
    pointer-events:none;
    transition:opacity .16s ease;
  }
  .cred-pill.copied .cred-overlay{opacity:1}

  .buyer-line{
    margin-top:8px;
    font-size:12px;
    color:var(--text-muted);
  }
  .buyer-line a{
    color:var(--accent);
    text-decoration:none;
    font-weight:600;
  }

  .actions{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    margin-top:10px;
  }
  .btn{
    border-radius:999px;
    padding:7px 12px;
    border:none;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
    text-decoration:none;
  }
  .btn-ghost{
    background:rgba(255,255,255,0.05);
    border:1px solid rgba(255,255,255,0.14);
    color:var(--text-main);
  }
  .btn-danger{
    background:linear-gradient(120deg,#ff7675,#ff9f9a);
    color:white;
  }
  .btn-primary{
    background:linear-gradient(120deg,var(--accent),var(--accent-soft));
    color:white;
  }

  footer{
    margin-top:18px;
    text-align:center;
    font-size:13px;
    color:rgba(255,255,255,0.75);
  }

  @media(max-width:820px){
    .acct{flex-direction:column}
    .acct-img{width:100%;height:190px}
  }
  @media(max-width:720px){
    .top-bar{flex-direction:column;align-items:flex-start}
    .nav-pill{align-self:flex-end}
  }
</style>
</head>
<body>
<div class="shell">
  <div class="top-bar">
    <div class="title-wrap">
      <h1>Accounts</h1>
      <div class="subtitle">Manage all uploaded accounts, grouped by category.</div>
    </div>
    <div class="nav-pill">
      <a href="manage_categories.php">⚙️ Categories</a>
      <a href="upload_account.php">📤 Upload</a>
    </div>
  </div>

  <?php if($msg): ?><div class="notice ok"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
  <?php if($err): ?><div class="notice err"><?= htmlspecialchars($err) ?></div><?php endif; ?>

  <?php if(empty($groups)): ?>
    <div class="category-card">
      <div class="cat-title">No accounts yet</div>
      <div class="cat-meta">Use the Upload page to add your first account.</div>
    </div>
  <?php else: ?>

    <?php foreach($groups as $catTitle => $list): ?>
      <div class="category-card">
        <div class="cat-header">
          <div class="cat-title"><?= htmlspecialchars($catTitle) ?></div>
          <div class="cat-meta"><?= count($list) ?> account(s)</div>
        </div>

        <?php foreach($list as $r): ?>
          <?php
            $buyer = ((int)$r['is_sold'] === 1) ? getLatestBuyer($pdo, $r['id']) : null;
            $level = $r['level'] ?? null;
            $gmail = $r['gmail'] ?? null;

            // order count for force delete badge
            $ocStmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE account_id = ?");
            $ocStmt->execute([$r['id']]);
            $orderCount = (int)$ocStmt->fetchColumn();
          ?>
          <div class="acct" id="acc-<?= (int)$r['id'] ?>">
            <div class="acct-img">
              <?php if(!empty($r['image_path'])): ?>
                <img src="../uploads/<?= htmlspecialchars($r['image_path']) ?>" alt="">
              <?php else: ?>
                <span style="font-size:12px;color:var(--text-muted)">No image</span>
              <?php endif; ?>
            </div>

            <div class="acct-body">
              <div class="acct-title-row">
                <div class="acct-title"><?= htmlspecialchars($r['title'] ?: 'Account') ?></div>
                <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
                  <?php if((int)$r['is_sold'] === 1): ?>
                    <span class="badge-sold">SOLD</span>
                  <?php endif; ?>
                  <?php if($r['price'] !== null && $r['price'] !== ''): ?>
                    <span class="badge-price">₹<?= number_format((float)$r['price'],2) ?></span>
                  <?php endif; ?>
                </div>
              </div>

              <div class="caption-box">
                <?= nl2br(htmlspecialchars($r['caption'] ?? '')) ?>
              </div>

              <div class="meta-row">
                <?php if(!empty($level)): ?>
                  <div class="meta-pill">⚡ Level: <?= htmlspecialchars($level) ?></div>
                <?php endif; ?>
                <?php if(!empty($gmail)): ?>
                  <div class="meta-pill">✉️ Gmail: <?= htmlspecialchars($gmail) ?></div>
                <?php endif; ?>
              </div>

              <div class="creds-row">
                <div class="cred-pill" data-copy="<?= htmlspecialchars($r['username_value'] ?? '', ENT_QUOTES) ?>">
                  <span class="cred-icon">👤</span>
                  <span class="cred-value"><?= htmlspecialchars($r['username_value'] ?: '—') ?></span>
                  <div class="cred-overlay">Copied</div>
                </div>
                <div class="cred-pill" data-copy="<?= htmlspecialchars($r['password_value'] ?? '', ENT_QUOTES) ?>">
                  <span class="cred-icon">🔑</span>
                  <span class="cred-value"><?= htmlspecialchars($r['password_value'] ?: '—') ?></span>
                  <div class="cred-overlay">Copied</div>
                </div>
              </div>

              <?php if($buyer): ?>
                <?php
                  $tgUser = $buyer['username'] ?: $buyer['telegram_id'];
                  $tgLink = $buyer['username']
                      ? "https://t.me/".urlencode($buyer['username'])
                      : "https://t.me/".urlencode($buyer['telegram_id']);
                ?>
                <div class="buyer-line">
                  🧾 Latest buyer:
                  <a href="<?= $tgLink ?>" target="_blank" rel="noopener">@<?= htmlspecialchars($tgUser) ?></a>
                </div>
              <?php endif; ?>

              <div class="actions">
                <a class="btn btn-ghost"
                   href="?delete=<?= (int)$r['id'] ?>"
                   onclick="return confirm('Delete this account? If it has orders, you will need Force Delete to remove them.')">
                  🗑️ Delete
                </a>

                <?php if($orderCount > 0): ?>
                  <a class="btn btn-danger"
                     href="?delete=<?= (int)$r['id'] ?>&confirm=yes"
                     onclick="return confirm('Force delete will remove this account AND <?= $orderCount ?> related order(s). Continue?')">
                    💥 Force Delete (<?= $orderCount ?>)
                  </a>
                <?php endif; ?>

                <a class="btn btn-primary" href="edit_account.php?id=<?= (int)$r['id'] ?>">✏️ Edit</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>

      </div>
    <?php endforeach; ?>

  <?php endif; ?>

  <footer>⚡ Managed by your bot admin panel</footer>
</div>

<script>
  // expand/collapse caption
  document.querySelectorAll('.caption-box').forEach(box => {
    box.addEventListener('click', () => {
      box.classList.toggle('expanded');
    });
  });

  // copy creds with toast overlay
  document.querySelectorAll('.cred-pill').forEach(el => {
    el.addEventListener('click', async () => {
      const txt = el.getAttribute('data-copy') || '';
      if (!txt) return;
      try {
        await navigator.clipboard.writeText(txt);
      } catch (e) {
        try {
          const ta = document.createElement('textarea');
          ta.value = txt;
          document.body.appendChild(ta);
          ta.select();
          document.execCommand('copy');
          ta.remove();
        } catch (_) {}
      }
      el.classList.add('copied');
      setTimeout(() => el.classList.remove('copied'), 900);
    });
  });
</script>
</body>
</html>