<?php
declare(strict_types=1);
/**
 * super_panel.php — IP Management Panel
 *
 * Accessible after normal login OR super_login.php.
 * Shows all admin accounts and lets you update allowed_ip.
 * Also allows setting the super_access_key.
 */
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';

// Must be logged in (normal or super session)
if (!lk_is_admin()) {
    header('Location: /super_login.php');
    exit;
}

$pdo     = lk_pdo();
$myIp    = lk_client_ip();
$msg     = '';
$msgType = 'ok';

// ── Handle POST actions ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF check
    $csrf = (string)($_POST['csrf'] ?? '');
    if (!hash_equals(lk_csrf_token(), $csrf)) {
        $msg = 'Security check failed. Refresh and try again.';
        $msgType = 'err';
    } else {
        $act = (string)($_POST['act'] ?? '');

        // Update allowed_ip for an admin
        if ($act === 'update_ip') {
            $adminId = (int)($_POST['admin_id'] ?? 0);
            $newIp   = trim((string)($_POST['new_ip'] ?? ''));
            if ($adminId <= 0) {
                $msg = 'Invalid admin ID.'; $msgType = 'err';
            } elseif ($newIp !== '' && !filter_var($newIp, FILTER_VALIDATE_IP)) {
                $msg = 'Invalid IP address format.'; $msgType = 'err';
            } else {
                $pdo->prepare("UPDATE admins SET allowed_ip=? WHERE id=?")
                    ->execute([$newIp, $adminId]);
                $msg = $newIp === ''
                    ? "IP restriction removed for admin #{$adminId}. Anyone can now log in."
                    : "Allowed IP updated to <b>{$newIp}</b> for admin #{$adminId}.";
            }
        }

        // Set this IP as my allowed_ip
        if ($act === 'approve_my_ip') {
            $adminId = (int)($_POST['admin_id'] ?? 0);
            if ($adminId <= 0) {
                $msg = 'Invalid admin ID.'; $msgType = 'err';
            } else {
                $pdo->prepare("UPDATE admins SET allowed_ip=? WHERE id=?")->execute([$myIp, $adminId]);
                $msg = "Your current IP <b>{$myIp}</b> is now the allowed IP for admin #{$adminId}.";
            }
        }

        // Update super_access_key
        if ($act === 'set_super_key') {
            $newKey = trim((string)($_POST['new_super_key'] ?? ''));
            if (mb_strlen($newKey) < 12) {
                $msg = 'Super key must be at least 12 characters.'; $msgType = 'err';
            } else {
                $pdo->prepare("INSERT INTO settings (`key`,`value`) VALUES ('super_access_key',?) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)")
                    ->execute([$newKey]);
                $msg = 'Super key updated.';
            }
        }
    }
}

// ── Load data ──
$admins   = $pdo->query("SELECT id, username, allowed_ip, is_active, created_at FROM admins ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$kSt      = $pdo->query("SELECT value FROM settings WHERE `key`='super_access_key' LIMIT 1");
$kRow     = $kSt ? $kSt->fetch(PDO::FETCH_ASSOC) : null;
$superKeySet = $kRow && trim((string)($kRow['value'] ?? '')) !== '';

$csrf = lk_csrf_token();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Super Panel — IP Management</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;900&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#0b1120;--card:#111c35;--card2:#162038;--bd:rgba(255,255,255,.08);
  --txt:#e2e8f0;--muted:rgba(226,232,240,.55);
  --a1:#f59e0b;--a2:#d97706;--green:#10b981;--bad:#ef4444;
}
body{min-height:100dvh;background:var(--bg);font-family:'Inter',sans-serif;color:var(--txt);padding:24px 16px;}
body::before{
  content:'';position:fixed;inset:0;pointer-events:none;z-index:0;
  background:radial-gradient(ellipse 60% 50% at 20% 20%,rgba(245,158,11,.10),transparent);
}
.wrap{position:relative;z-index:1;max-width:740px;margin:0 auto;}
.topBar{display:flex;align-items:center;justify-content:space-between;margin-bottom:28px;gap:12px;flex-wrap:wrap;}
.topBar h1{font-size:20px;font-weight:900;}
.topBar a{font-size:13px;color:var(--muted);text-decoration:none;padding:8px 14px;border:1px solid var(--bd);border-radius:10px;}
.topBar a:hover{color:var(--txt);}
.myIpBadge{font-size:12px;color:var(--a1);font-weight:700;background:rgba(245,158,11,.12);padding:6px 12px;border-radius:8px;border:1px solid rgba(245,158,11,.25);}
.msg{padding:12px 16px;border-radius:12px;font-size:14px;font-weight:700;margin-bottom:20px;line-height:1.5;}
.msg.ok{background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.3);color:#6ee7b7;}
.msg.err{background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.3);color:#fca5a5;}
.section{background:var(--card);border:1px solid var(--bd);border-radius:18px;margin-bottom:20px;overflow:hidden;}
.sHead{padding:16px 20px;border-bottom:1px solid var(--bd);font-size:15px;font-weight:800;display:flex;align-items:center;gap:8px;}
.sBody{padding:16px 20px;}
.adminCard{background:var(--card2);border:1px solid var(--bd);border-radius:14px;padding:16px 18px;margin-bottom:14px;}
.adminCard:last-child{margin-bottom:0;}
.adminTop{display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap;}
.adminName{font-size:16px;font-weight:800;}
.tag{font-size:11px;font-weight:700;padding:3px 9px;border-radius:6px;letter-spacing:.3px;}
.tag.active{background:rgba(16,185,129,.15);border:1px solid rgba(16,185,129,.3);color:#6ee7b7;}
.tag.inactive{background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.28);color:#fca5a5;}
.ipLine{font-size:13px;color:var(--muted);margin-bottom:14px;font-family:monospace;}
.ipLine b{color:var(--txt);}
.ipLine .none{color:rgba(239,68,68,.8);font-style:italic;}
.formRow{display:flex;gap:8px;flex-wrap:wrap;}
.inp{
  flex:1;min-width:160px;padding:10px 14px;
  background:rgba(255,255,255,.05);border:1px solid var(--bd);border-radius:10px;
  color:var(--txt);font-size:14px;font-family:inherit;outline:none;transition:border-color .2s;
}
.inp:focus{border-color:var(--a1);}
.btn{
  padding:10px 16px;border:none;border-radius:10px;cursor:pointer;font-size:13px;
  font-weight:800;font-family:inherit;white-space:nowrap;transition:opacity .15s;
}
.btn:hover{opacity:.85;}
.btn.gold{background:linear-gradient(135deg,var(--a1),var(--a2));color:#fff;}
.btn.green{background:linear-gradient(135deg,var(--green),#059669);color:#fff;}
.btn.red{background:rgba(239,68,68,.2);border:1px solid rgba(239,68,68,.35);color:#fca5a5;}
.superKeyForm{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}
.hint{font-size:12px;color:var(--muted);margin-top:8px;line-height:1.6;}
.divider{height:1px;background:var(--bd);margin:14px 0;}
</style>
</head>
<body>
<div class="wrap">
  <div class="topBar">
    <h1>🔑 IP Management Panel</h1>
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
      <span class="myIpBadge">Your IP: <?= lk_e($myIp) ?></span>
      <a href="/">← Dashboard</a>
    </div>
  </div>

  <?php if ($msg !== ''): ?>
    <div class="msg <?= $msgType ?>"><?= $msg ?></div>
  <?php endif; ?>

  <!-- Admin Accounts -->
  <div class="section">
    <div class="sHead">👤 Admin Accounts</div>
    <div class="sBody">
      <?php foreach ($admins as $a): ?>
        <?php
        $aid      = (int)$a['id'];
        $aUser    = lk_e((string)$a['username']);
        $aIp      = trim((string)($a['allowed_ip'] ?? ''));
        $aActive  = (int)$a['is_active'] === 1;
        $isMyIp   = ($aIp === $myIp);
        ?>
        <div class="adminCard">
          <div class="adminTop">
            <span class="adminName"><?= $aUser ?></span>
            <span class="tag <?= $aActive ? 'active' : 'inactive' ?>"><?= $aActive ? 'ACTIVE' : 'INACTIVE' ?></span>
            <span class="tag" style="background:rgba(255,255,255,.06);border:1px solid var(--bd);color:var(--muted);">ID #<?= $aid ?></span>
          </div>
          <div class="ipLine">
            Allowed IP:
            <?php if ($aIp !== '' && $aIp !== '0.0.0.0'): ?>
              <b><?= lk_e($aIp) ?></b>
              <?php if ($isMyIp): ?><span style="color:var(--green);margin-left:6px;">✓ (your IP)</span><?php endif; ?>
            <?php else: ?>
              <span class="none">None (anyone can log in)</span>
            <?php endif; ?>
          </div>

          <!-- Approve my IP button -->
          <form method="post" style="margin-bottom:10px;">
            <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
            <input type="hidden" name="act" value="approve_my_ip">
            <input type="hidden" name="admin_id" value="<?= $aid ?>">
            <button class="btn green" type="submit">✓ Set My Current IP (<?= lk_e($myIp) ?>)</button>
          </form>

          <!-- Manual IP update -->
          <form method="post" class="formRow">
            <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
            <input type="hidden" name="act" value="update_ip">
            <input type="hidden" name="admin_id" value="<?= $aid ?>">
            <input class="inp" type="text" name="new_ip" placeholder="Custom IP (leave empty = no restriction)"
              value="<?= lk_e($aIp) ?>" maxlength="45">
            <button class="btn gold" type="submit">Save IP</button>
            <?php if ($aIp !== '' && $aIp !== '0.0.0.0'): ?>
              <button class="btn red" type="submit" onclick="document.querySelector('input[name=new_ip]').value=''">Remove Restriction</button>
            <?php endif; ?>
          </form>
          <div class="hint">Leave IP blank to allow login from any IP (less secure).</div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Super Key Management -->
  <div class="section">
    <div class="sHead">🗝️ Super Key Settings</div>
    <div class="sBody">
      <p style="font-size:14px;color:var(--muted);margin-bottom:14px;line-height:1.6;">
        The Super Key is the secret required to use <b>super_login.php</b> for IP bypass.<br>
        Status: <?php if ($superKeySet): ?><span style="color:var(--green);font-weight:700;">✓ Key is set</span><?php else: ?><span style="color:var(--bad);font-weight:700;">✗ Not set yet</span><?php endif; ?>
      </p>
      <form method="post" class="superKeyForm">
        <input type="hidden" name="csrf" value="<?= lk_e($csrf) ?>">
        <input type="hidden" name="act" value="set_super_key">
        <input class="inp" type="text" name="new_super_key" placeholder="New super key (min 12 chars)" minlength="12" required>
        <button class="btn gold" type="submit">Set Super Key</button>
      </form>
      <div class="hint">⚠️ Keep this key private. Anyone with this key + valid credentials can log in from any IP.</div>
    </div>
  </div>

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