<?php
declare(strict_types=1);
require_once __DIR__ . '/auth.php';
require_admin();
require_once __DIR__ . '/layout.php';

$pdo  = lk_pdo();
$csrf = lk_csrf_token();
$flash = '';
$flashType = 'ok';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    lk_csrf_check();
    $act = (string)($_POST['act'] ?? '');

    if ($act === 'create_user') {
        $uname   = trim((string)($_POST['username'] ?? ''));
        $phone   = trim((string)($_POST['phone'] ?? ''));
        $passRaw = (string)($_POST['password'] ?? '');
        $balance = (float)($_POST['balance'] ?? 0);
        if ($uname === '' || $passRaw === '') {
            $flash = 'Username and password required.'; $flashType = 'bad';
        } else {
            try {
                $apiKey    = bin2hex(random_bytes(20));
                $apiSecret = bin2hex(random_bytes(32));
                $passHash  = password_hash($passRaw, PASSWORD_DEFAULT);
                $pdo->prepare("INSERT INTO users (username, phone, password_hash, api_key, api_secret_hash, api_secret_last4, balance, created_at) VALUES (?,?,?,?,?,?,?,NOW())")
                    ->execute([$uname, $phone ?: null, $passHash, $apiKey, $apiSecret, substr($apiSecret,-4), $balance]);
                $flash = "✅ User created! API Key: $apiKey | Secret: $apiSecret";
            } catch (Throwable $e) {
                $flash = 'Create failed: ' . $e->getMessage(); $flashType = 'bad';
            }
        }

    } elseif ($act === 'regen_key') {
        $uid2 = (int)($_POST['uid'] ?? 0);
        if ($uid2 > 0) {
            $newKey = bin2hex(random_bytes(20));
            $newSec = bin2hex(random_bytes(32));
            $pdo->prepare("UPDATE users SET api_key=?, api_secret_hash=?, api_secret_last4=? WHERE id=?")
                ->execute([$newKey, $newSec, substr($newSec,-4), $uid2]);
            $flash = "New Key: $newKey | Secret: $newSec";
        }

    } elseif ($act === 'adjust_balance') {
        $uid2  = (int)($_POST['uid'] ?? 0);
        $delta = (float)($_POST['delta'] ?? 0);
        if ($uid2 > 0) {
            $pdo->prepare("UPDATE users SET balance = GREATEST(0, balance + ?) WHERE id=?")->execute([$delta, $uid2]);
            $flash = 'Balance updated.';
        }

    } elseif ($act === 'toggle_active') {
        $uid2 = (int)($_POST['uid'] ?? 0);
        if ($uid2 > 0) {
            $pdo->prepare("UPDATE users SET is_active = IF(is_active=1,0,1) WHERE id=?")->execute([$uid2]);
            $flash = 'User status toggled.';
        }

    } elseif ($act === 'delete_user') {
        $uid2 = (int)($_POST['uid'] ?? 0);
        if ($uid2 > 0) {
            try {
                $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid2]);
                $flash = 'User deleted.';
            } catch (Throwable $e) {
                $flash = 'Delete failed: ' . $e->getMessage(); $flashType = 'bad';
            }
        }
    }
}

$users = [];
$dbError = '';
try {
    $users = $pdo->query("SELECT id, username, phone, api_key, api_secret_last4, balance, is_active, created_at FROM users ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $dbError = 'DB error: ' . $e->getMessage();
}

lk_layout_head('Users');
lk_layout_nav('users');
?>
<div class="page">
  <div class="page-head">
    <h2>API Users</h2>
    <p>Bot account ও API key manage করুন।</p>
  </div>

  <?php if ($flash !== ''): ?>
    <div class="flash flash-<?= $flashType==='ok'?'ok':'bad' ?>" style="word-break:break-all;"><?= lk_e($flash) ?></div>
  <?php endif; ?>
  <?php if ($dbError !== ''): ?>
    <div class="flash flash-bad"><?= lk_e($dbError) ?></div>
  <?php endif; ?>

  <!-- CREATE USER -->
  <div class="card" style="margin-bottom:20px;">
    <div class="sec-head">New User তৈরি করুন</div>
    <form method="post">
      <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
      <input type="hidden" name="act" value="create_user">
      <div class="grid-2">
        <div class="field">
          <label class="lbl">Username</label>
          <input class="inp" type="text" name="username" required>
        </div>
        <div class="field">
          <label class="lbl">Phone (optional)</label>
          <input class="inp" type="text" name="phone" placeholder="01XXXXXXXXX">
        </div>
        <div class="field">
          <label class="lbl">Password</label>
          <input class="inp" type="text" name="password" required>
        </div>
        <div class="field">
          <label class="lbl">Initial Balance (৳)</label>
          <input class="inp" type="number" name="balance" value="0" step="0.01" min="0">
        </div>
      </div>
      <button class="btn btn-green" type="submit">➕ Create User</button>
    </form>
  </div>

  <!-- USERS TABLE -->
  <div class="card">
    <div class="sec-head">All Users (<?= count($users) ?>)</div>
    <div style="overflow-x:auto;">
    <table class="tbl">
      <thead>
        <tr><th>#</th><th>Username</th><th>Phone</th><th>API Key</th><th>Secret Last4</th><th>Balance</th><th>Status</th><th>Actions</th></tr>
      </thead>
      <tbody>
        <?php foreach ($users as $u):
          $active = (int)($u['is_active'] ?? 1) === 1;
        ?>
        <tr>
          <td style="color:var(--muted);font-size:11px;"><?= (int)$u['id'] ?></td>
          <td><strong><?= lk_e((string)($u['username'] ?? '')) ?></strong></td>
          <td style="font-size:12px;color:var(--muted);"><?= lk_e((string)($u['phone'] ?? '—')) ?></td>
          <td><code style="font-size:11px;color:var(--gold);word-break:break-all;"><?= lk_e((string)($u['api_key'] ?? '')) ?></code></td>
          <td><code style="color:var(--a3);font-weight:900;">...<?= lk_e((string)($u['api_secret_last4'] ?? '????')) ?></code></td>
          <td><strong style="color:var(--a3);">৳<?= number_format((float)($u['balance'] ?? 0), 2) ?></strong></td>
          <td>
            <span class="badge <?= $active ? 'badge-green' : 'badge-red' ?>"><?= $active ? 'Active' : 'Inactive' ?></span>
          </td>
          <td>
            <div style="display:flex;gap:6px;flex-wrap:wrap;">
              <!-- Regen Key -->
              <form method="post" style="display:inline;" onsubmit="return confirm('Regenerate API key for <?= lk_e((string)$u['username']) ?>?');">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="regen_key">
                <input type="hidden" name="uid" value="<?= (int)$u['id'] ?>">
                <button class="btn btn-gold btn-sm" type="submit">🔑 Regen</button>
              </form>
              <!-- Adjust Balance -->
              <form method="post" style="display:inline-flex;gap:4px;align-items:center;">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="adjust_balance">
                <input type="hidden" name="uid" value="<?= (int)$u['id'] ?>">
                <input class="inp" type="number" name="delta" placeholder="±amount" style="width:90px;padding:5px 8px;font-size:12px;" step="0.01">
                <button class="btn btn-ghost btn-sm" type="submit">৳</button>
              </form>
              <!-- Toggle Active -->
              <form method="post" style="display:inline;">
                <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
                <input type="hidden" name="act" value="toggle_active">
                <input type="hidden" name="uid" value="<?= (int)$u['id'] ?>">
                <button class="btn btn-ghost btn-sm" type="submit"><?= $active ? '🔒 Disable' : '✅ Enable' ?></button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($users)): ?>
          <tr><td colspan="8" style="text-align:center;color:var(--muted);padding:28px;">No users yet.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
    </div>
  </div>
</div>
<?php lk_layout_foot(); ?>
