<?php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/acl.php';
require_once __DIR__ . '/../app/credits.php';
require_login();

$me = current_user();
$pdo = db();

$msg = null;
$err = null;

$downline = get_downline((int)$me['id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_credits') {
      if ($me['role'] !== 'admin') throw new Exception("Only admin can add credits directly.");
      $userId = (int)($_POST['user_id'] ?? 0);
      $amount = (float)($_POST['amount'] ?? 0);
      if ($userId <= 0) throw new Exception("User required");
      if ($amount == 0) throw new Exception("Amount required");

      credit_adjust($userId, $amount, 'admin_adjust', "Admin adjustment", (int)$me['id']);
      $msg = "Adjusted credits for user #{$userId} by {$amount}.";
    }

    if ($action === 'transfer') {
      $toUserId = (int)($_POST['to_user_id'] ?? 0);
      $amount   = (float)($_POST['amount'] ?? 0);
      if ($toUserId <= 0) throw new Exception("Recipient required");
      if ($amount <= 0) throw new Exception("Amount must be > 0");

      // Must be in downline
      if (!can_manage_user((int)$me['id'], $toUserId)) throw new Exception("Recipient not in your downline");

      credit_transfer((int)$me['id'], $toUserId, $amount, (int)$me['id']);
      $msg = "Transferred {$amount} credits to user #{$toUserId}.";
    }

  } catch (Exception $e) {
    $err = $e->getMessage();
  }
}

// Ledger for me
$st = $pdo->prepare("SELECT * FROM credit_ledger WHERE user_id=? ORDER BY id DESC LIMIT 200");
$st->execute([(int)$me['id']]);
$ledger = $st->fetchAll();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Credits</title>
  <style>
    body{font-family:system-ui;margin:0;background:#0b1220;color:#e6e6e6}
    .wrap{max-width:1100px;margin:0 auto;padding:18px}
    .top{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
    .nav a{margin-right:12px;color:#93c5fd;text-decoration:none}
    .card{background:#111a2e;border:1px solid #233055;border-radius:16px;padding:16px;margin-top:14px}
    input,select{width:100%;padding:10px;border-radius:12px;border:1px solid #2a3a66;background:#0b1220;color:#fff;margin:6px 0}
    button{padding:10px 12px;border-radius:12px;border:0;background:#3b82f6;color:#fff;font-weight:600;cursor:pointer}
    table{width:100%;border-collapse:collapse;margin-top:10px}
    th,td{padding:10px;border-bottom:1px solid #233055;text-align:left;font-size:14px}
    .ok{background:#0f2a1a;border:1px solid #1f6b3a;padding:10px;border-radius:12px}
    .bad{background:#2a1220;border:1px solid #6b2142;padding:10px;border-radius:12px}
    .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
    @media (max-width:900px){.grid{grid-template-columns:1fr}}
  </style>
</head>
<body>
  <div class="wrap">
    <div class="top">
      <div class="nav">
        <a href="/dashboard.php">Dashboard</a>
        <a href="/users.php">Users</a>
        <a href="/credits.php">Credits</a>
      </div>
      <div><a style="color:#93c5fd" href="/logout.php">Logout</a></div>
    </div>

    <div class="card">
      <h2 style="margin:0;">My credits: <?= number_format((float)$me['credits_balance'], 2) ?></h2>
      <?php if ($msg): ?><div style="margin-top:10px" class="ok"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
      <?php if ($err): ?><div style="margin-top:10px" class="bad"><?= htmlspecialchars($err) ?></div><?php endif; ?>
    </div>

    <div class="card">
      <h3 style="margin:0 0 6px 0;">Transfer credits to downline</h3>
      <form method="post">
        <input type="hidden" name="action" value="transfer" />
        <div class="grid">
          <div>
            <label>To user</label>
            <select name="to_user_id" required>
              <?php foreach ($downline as $u): ?>
                <option value="<?= (int)$u['id'] ?>">
                  <?= htmlspecialchars(($u['display_name'] ?: $u['username']) . " (#{$u['id']} / {$u['role']})") ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>Amount</label>
            <input name="amount" type="number" step="0.01" min="0.01" required />
          </div>
        </div>
        <div style="margin-top:10px;">
          <button type="submit">Transfer</button>
        </div>
      </form>
    </div>

    <?php if ($me['role'] === 'admin'): ?>
    <div class="card">
      <h3 style="margin:0 0 6px 0;">Admin: adjust credits</h3>
      <form method="post">
        <input type="hidden" name="action" value="add_credits" />
        <div class="grid">
          <div>
            <label>User ID</label>
            <input name="user_id" type="number" required />
          </div>
          <div>
            <label>Amount (use negative to subtract)</label>
            <input name="amount" type="number" step="0.01" required />
          </div>
        </div>
        <div style="margin-top:10px;">
          <button type="submit">Apply</button>
        </div>
      </form>
    </div>
    <?php endif; ?>

    <div class="card">
      <h3 style="margin:0 0 6px 0;">My ledger (latest 200)</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th><th>When</th><th>Reason</th><th>Delta</th><th>Before</th><th>After</th><th>Note</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$ledger): ?>
            <tr><td colspan="7" style="opacity:.75;">No ledger entries yet.</td></tr>
          <?php endif; ?>
          <?php foreach ($ledger as $l): ?>
            <tr>
              <td><?= (int)$l['id'] ?></td>
              <td><?= htmlspecialchars($l['created_at']) ?></td>
              <td><?= htmlspecialchars($l['reason']) ?></td>
              <td><?= htmlspecialchars($l['delta']) ?></td>
              <td><?= htmlspecialchars($l['before_balance']) ?></td>
              <td><?= htmlspecialchars($l['after_balance']) ?></td>
              <td><?= htmlspecialchars($l['note'] ?: '-') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

  </div>
</body>
</html>
