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

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

$msg = null;
$err = null;

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

    if ($action === 'create_user') {
      $username = trim($_POST['username'] ?? '');
      $password = trim($_POST['password'] ?? '');
      $display  = trim($_POST['display_name'] ?? '');
      $role     = trim($_POST['role'] ?? 'seller');
      $parentId = (int)($_POST['parent_id'] ?? 0);

      if ($username === '' || $password === '') throw new Exception("Username and password are required");
      if (!in_array($role, ['reseller','seller'], true)) throw new Exception("Invalid role");
      if ($parentId <= 0) throw new Exception("Parent is required");

      // Only allow creating under your own downline (or yourself)
      if (!can_manage_user((int)$me['id'], $parentId)) throw new Exception("You cannot create under that parent");

      // Only admin can create a reseller directly under them (you can adjust this policy later)
      if ($role === 'reseller' && $me['role'] !== 'admin') throw new Exception("Only admin can create resellers");

      $hash = password_hash($password, PASSWORD_BCRYPT);

      $st = $pdo->prepare("INSERT INTO users (parent_id, role, username, password_hash, display_name, credits_balance)
                           VALUES (?,?,?,?,?,0)");
      $st->execute([$parentId, $role, $username, $hash, $display ?: null]);

      $msg = "Created user: {$username} ({$role})";
    }

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

// Parent dropdown: user can create under themselves or their downline
$parents = array_merge([[
  'id' => $me['id'],
  'label' => 'Me (' . $me['username'] . ')'
]], array_map(function($u){
  return ['id' => $u['id'], 'label' => ($u['display_name'] ?: $u['username']) . " (#{$u['id']} / {$u['role']})"];
}, get_downline((int)$me['id'])));

$downline = get_downline((int)$me['id']);
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Users</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 0 6px 0;">Create user</h2>
      <div style="opacity:.75;margin-bottom:10px;">Create sellers under you (and admin can create resellers).</div>

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

      <form method="post">
        <input type="hidden" name="action" value="create_user" />
        <div class="grid">
          <div>
            <label>Parent</label>
            <select name="parent_id" required>
              <?php foreach ($parents as $p): ?>
                <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['label']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>Role</label>
            <select name="role">
              <?php if ($me['role'] === 'admin'): ?>
                <option value="reseller">reseller</option>
              <?php endif; ?>
              <option value="seller" selected>seller</option>
            </select>
          </div>
          <div>
            <label>Username</label>
            <input name="username" required />
          </div>
          <div>
            <label>Password</label>
            <input name="password" type="password" required />
          </div>
          <div>
            <label>Display name (optional)</label>
            <input name="display_name" />
          </div>
        </div>
        <div style="margin-top:10px;">
          <button type="submit">Create</button>
        </div>
      </form>
    </div>

    <div class="card">
      <h2 style="margin:0 0 6px 0;">My downline</h2>
      <div style="opacity:.75;">All users below you (children + descendants).</div>

      <table>
        <thead>
          <tr>
            <th>ID</th><th>Role</th><th>Username</th><th>Name</th><th>Active</th><th>Credits</th><th>Created</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$downline): ?>
            <tr><td colspan="7" style="opacity:.75;">No users yet.</td></tr>
          <?php endif; ?>
          <?php foreach ($downline as $u): ?>
            <tr>
              <td><?= (int)$u['id'] ?></td>
              <td><?= htmlspecialchars($u['role']) ?></td>
              <td><?= htmlspecialchars($u['username']) ?></td>
              <td><?= htmlspecialchars($u['display_name'] ?: '-') ?></td>
              <td><?= (int)$u['is_active'] ? 'Yes' : 'No' ?></td>
              <td><?= number_format((float)$u['credits_balance'], 2) ?></td>
              <td><?= htmlspecialchars($u['created_at']) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

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