<?php
require '../config.php';
require_login();

// If you have your own admin check, use it.
// Fallback:
if (!function_exists('require_admin')) {
  function require_admin(){
    if (empty($_SESSION['role']) || $_SESSION['role']!=='admin') {
      set_flash("Admin only.", "danger");
      redirect('../index.php');
    }
  }
}
require_admin();

if (!function_exists('h')) { function h($s){ return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8'); } }

// accept / reject actions
if (is_post()) {
  verify_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $act = $_POST['action'] ?? '';
  if ($id>0 && in_array($act,['accept','reject'],true)) {
    // fetch row
    $st = $pdo->prepare("SELECT * FROM activation_payments WHERE id=? AND status='pending'");
    $st->execute([$id]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if ($row) {
      if ($act==='accept') {
        $pdo->beginTransaction();
        try {
          $pdo->prepare("UPDATE activation_payments SET status='accepted' WHERE id=?")->execute([$id]);
          $pdo->prepare("UPDATE users SET is_active=1, activation_paid=1 WHERE id=?")->execute([$row['user_id']]);
          $pdo->commit();
          set_flash("Activation accepted & user activated ✅", "success");
        } catch(Exception $e){
          $pdo->rollBack();
          set_flash("Failed: ".$e->getMessage(), "danger");
        }
      } else {
        $pdo->prepare("UPDATE activation_payments SET status='rejected' WHERE id=?")->execute([$id]);
        set_flash("Activation rejected.", "warning");
      }
    }
  }
  redirect('activations.php');
}

// load lists
$pending = $pdo->query("SELECT ap.*, u.email FROM activation_payments ap JOIN users u ON u.id=ap.user_id WHERE ap.status='pending' ORDER BY ap.id DESC")->fetchAll(PDO::FETCH_ASSOC);
$recent  = $pdo->query("SELECT ap.*, u.email FROM activation_payments ap JOIN users u ON u.id=ap.user_id WHERE ap.status<>'pending' ORDER BY ap.id DESC LIMIT 20")->fetchAll(PDO::FETCH_ASSOC);

require_once 'header.php'; // your admin header
?>
<style>
:root{ --border:#e6eaf5; --muted:#64748b; --grad1:#4f8cff; --grad2:#7a5cff; }
.wrap{ max-width:1100px; margin:16px auto; }
.card{ border:1px solid var(--border); border-radius:16px; padding:14px; background:#fff; box-shadow:0 8px 22px rgba(15,23,42,.08); }
.card h5{ margin:0 0 10px; }
.badge{ padding:4px 8px; border-radius:999px; font-weight:700; font-size:.75rem }
.btnx{ border:0; border-radius:10px; padding:.45rem .7rem; font-weight:700; }
.btn-accept{ background:linear-gradient(90deg,var(--grad1),var(--grad2)); color:#fff; }
.btn-reject{ background:#ffe2e2; color:#9b1c1c; }
.small{ color:var(--muted) }
table td, table th{ vertical-align:middle }
</style>

<div class="wrap">
  <?php show_flash(); ?>

  <div class="card mb-3">
    <h5>Pending Activations</h5>
    <?php if(!$pending): ?>
      <div class="small">No pending requests.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead><tr>
            <th>ID</th><th>User</th><th>Amount</th><th>Method</th><th>Sender</th><th>TRXID</th><th>Requested</th><th>Action</th>
          </tr></thead>
          <tbody>
          <?php foreach($pending as $p): ?>
            <tr>
              <td>#<?= (int)$p['id'] ?></td>
              <td><?= h($p['email']) ?></td>
              <td>৳ <?= number_format($p['amount'], 2) ?></td>
              <td><?= h($p['method']) ?></td>
              <td><?= h($p['sender']) ?></td>
              <td><code><?= h($p['trxid']) ?></code></td>
              <td class="small"><?= h($p['created_at']) ?></td>
              <td>
                <form method="post" class="d-inline">
                  <?php csrf_field(); ?>
                  <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                  <button name="action" value="accept" class="btnx btn-accept">Accept</button>
                </form>
                <form method="post" class="d-inline">
                  <?php csrf_field(); ?>
                  <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                  <button name="action" value="reject" class="btnx btn-reject">Reject</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

  <div class="card">
    <h5>Recent Decisions</h5>
    <?php if(!$recent): ?>
      <div class="small">No recent decisions.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead><tr>
            <th>ID</th><th>User</th><th>Amount</th><th>Method</th><th>Sender</th><th>TRXID</th><th>Status</th><th>When</th>
          </tr></thead>
          <tbody>
          <?php foreach($recent as $p): ?>
            <tr>
              <td>#<?= (int)$p['id'] ?></td>
              <td><?= h($p['email']) ?></td>
              <td>৳ <?= number_format($p['amount'], 2) ?></td>
              <td><?= h($p['method']) ?></td>
              <td><?= h($p['sender']) ?></td>
              <td><code><?= h($p['trxid']) ?></code></td>
              <td>
                <?php if($p['status']==='accepted'): ?>
                  <span class="badge bg-success">Accepted</span>
                <?php elseif($p['status']==='rejected'): ?>
                  <span class="badge bg-danger">Rejected</span>
                <?php endif; ?>
              </td>
              <td class="small"><?= h($p['created_at']) ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php require_once 'footer.php'; ?>
