<?php
// ============================================================
// admin/index.php — Admin Panel (password protected)
// ============================================================
require_once __DIR__ . '/../config.php';
session_name('fg_admin_session');
session_start();

$error = '';
$msg   = '';

// ── Admin Login ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_login'])) {
    if ($_POST['admin_pass'] === ADMIN_PASSWORD) {
        $_SESSION['fg_admin'] = true;
    } else {
        $error = 'Password admin salah.';
    }
}

if (isset($_POST['admin_logout'])) {
    $_SESSION['fg_admin'] = false;
    session_destroy();
    header('Location: index.php');
    exit;
}

$isAdmin = !empty($_SESSION['fg_admin']);

// ── User Actions (only if admin) ─────────────────────────────
if ($isAdmin) {
    $db = getDB();

    // Add user
    if (isset($_POST['add_user'])) {
        $u  = trim($_POST['username']);
        $e  = trim($_POST['email']);
        $p  = $_POST['password'];
        $fn = trim($_POST['full_name']);
        $co = trim($_POST['company']);
        $ro = $_POST['role'];
        $no = trim($_POST['notes']);
        $exp = ($ro === 'trial') ? date('Y-m-d H:i:s', time() + intval($_POST['trial_hours'] ?? 24) * 3600) : null;
        try {
            $hash = password_hash($p, PASSWORD_DEFAULT);
            $db->prepare("INSERT INTO fg_users (username,email,password_hash,role,full_name,company,notes,trial_expires_at) VALUES (?,?,?,?,?,?,?,?)")
               ->execute([$u,$e,$hash,$ro,$fn,$co,$no,$exp]);
            $msg = "User <strong>$u</strong> berhasil ditambahkan.";
        } catch (\Throwable $e2) { $error = 'Gagal: ' . $e2->getMessage(); }
    }

    // Update user
    if (isset($_POST['update_user'])) {
        $id   = intval($_POST['user_id']);
        $role = $_POST['role'];
        $exp  = ($role === 'trial') ? date('Y-m-d H:i:s', time() + intval($_POST['trial_hours'] ?? 24) * 3600) : null;
        $maxDev = intval($_POST['max_devices'] ?? 2);
        $db->prepare("UPDATE fg_users SET role=?,full_name=?,company=?,notes=?,trial_expires_at=?,max_devices=? WHERE id=?")
           ->execute([$role, $_POST['full_name'], $_POST['company'], $_POST['notes'], $exp, $maxDev, $id]);
        $msg = 'User diperbarui.';
    }

    // Delete user
    if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
        $db->prepare("DELETE FROM fg_users WHERE id=?")->execute([intval($_GET['delete'])]);
        $msg = 'User dihapus.';
        header('Location: index.php?msg=deleted');
        exit;
    }

    // Reset devices
    if (isset($_GET['reset_devices']) && is_numeric($_GET['reset_devices'])) {
        $uid = intval($_GET['reset_devices']);
        $db->prepare("DELETE FROM fg_user_devices WHERE user_id=?")->execute([$uid]);
        $msg = 'Device list user direset. User bisa login dari device baru.';
        header('Location: index.php');
        exit;
    }

    // Reset devices
    if (isset($_GET['reset_devices']) && is_numeric($_GET['reset_devices'])) {
        $uid = intval($_GET['reset_devices']);
        $db->prepare("DELETE FROM fg_user_devices WHERE user_id=?")->execute([$uid]);
        $msg = 'Device list direset. User bisa login dari device baru.';
        header('Location: index.php');
        exit;
    }

    // Extend trial
    if (isset($_GET['extend']) && is_numeric($_GET['extend'])) {
        $db->prepare("UPDATE fg_users SET trial_expires_at=DATE_ADD(NOW(), INTERVAL ? HOUR), role='trial' WHERE id=?")
           ->execute([intval($_GET['hours'] ?? 24), intval($_GET['extend'])]);
        $msg = 'Trial diperpanjang.';
    }

    $users = $db->query("SELECT * FROM fg_users ORDER BY created_at DESC")->fetchAll();
    $logs  = $db->query("SELECT l.*, u.username FROM fg_activity_log l LEFT JOIN fg_users u ON l.user_id=u.id ORDER BY l.created_at DESC LIMIT 60")->fetchAll();
    $stats = $db->query("SELECT role, COUNT(*) as cnt FROM fg_users GROUP BY role")->fetchAll(PDO::FETCH_KEY_PAIR);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin Panel — FortiGate Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',sans-serif;background:#0F1117;color:#E2E8F0;min-height:100vh}
a{color:#60A5FA;text-decoration:none}

/* ── Login ── */
.login-wrap{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:20px}
.login-box{background:#1A1D26;border:1px solid #2D3748;border-radius:12px;padding:36px;width:100%;max-width:400px}
.login-box h2{font-size:20px;font-weight:600;margin-bottom:6px}
.login-box p{font-size:13px;color:#94A3B8;margin-bottom:24px}
.fg-logo{display:flex;align-items:center;gap:10px;margin-bottom:24px}
.fg-logo-icon{width:40px;height:40px;background:linear-gradient(135deg,#E65100,#FF8F00);border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:18px}

/* ── Admin layout ── */
.admin-wrap{display:flex;min-height:100vh}
.sidebar{width:220px;background:#13151E;border-right:1px solid #1E2535;padding:20px 0;flex-shrink:0;position:sticky;top:0;height:100vh;overflow-y:auto}
.sidebar .brand{padding:0 20px 20px;border-bottom:1px solid #1E2535;margin-bottom:12px}
.sidebar .brand h3{font-size:14px;font-weight:600;color:#F1F5F9}
.sidebar .brand p{font-size:11px;color:#64748B;margin-top:2px}
.nav-item{display:flex;align-items:center;gap:8px;padding:9px 20px;font-size:13px;color:#94A3B8;cursor:pointer;transition:.15s}
.nav-item:hover,.nav-item.active{background:#1E2535;color:#E2E8F0}
.nav-item.active{border-right:2px solid #3B82F6}
.main{flex:1;padding:24px;overflow-y:auto}
.topbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px}
.topbar h1{font-size:18px;font-weight:600}

/* ── Cards ── */
.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px;margin-bottom:24px}
.stat-card{background:#1A1D26;border:1px solid #1E2535;border-radius:10px;padding:16px}
.stat-card .label{font-size:12px;color:#64748B;margin-bottom:4px}
.stat-card .val{font-size:26px;font-weight:600}
.stat-card .val.trial{color:#FBBF24}
.stat-card .val.registered{color:#34D399}
.stat-card .val.blocked{color:#F87171}

/* ── Tables ── */
.card{background:#1A1D26;border:1px solid #1E2535;border-radius:10px;overflow:hidden;margin-bottom:20px}
.card-header{padding:14px 18px;border-bottom:1px solid #1E2535;display:flex;align-items:center;justify-content:space-between}
.card-header h2{font-size:14px;font-weight:600}
table{width:100%;border-collapse:collapse;font-size:13px}
th{padding:10px 14px;text-align:left;font-size:11px;font-weight:500;color:#64748B;border-bottom:1px solid #1E2535;text-transform:uppercase;letter-spacing:.05em}
td{padding:10px 14px;border-bottom:1px solid #0F1117;color:#CBD5E1}
tr:last-child td{border-bottom:none}
tr:hover td{background:#1E2535}

/* ── Badges ── */
.badge{display:inline-block;font-size:11px;padding:2px 8px;border-radius:4px;font-weight:500}
.badge-trial{background:#451A03;color:#FBBF24}
.badge-registered{background:#022C22;color:#34D399}
.badge-blocked{background:#3B0606;color:#F87171}

/* ── Forms ── */
.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;padding:16px 18px}
.form-group label{display:block;font-size:12px;color:#94A3B8;margin-bottom:5px}
.form-group input,.form-group select,.form-group textarea{width:100%;background:#0F1117;border:1px solid #2D3748;border-radius:6px;padding:8px 10px;font-size:13px;color:#E2E8F0;font-family:inherit}
.form-group input:focus,.form-group select:focus{outline:none;border-color:#3B82F6}
.form-group textarea{resize:vertical;min-height:60px}
.btn{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:.15s}
.btn-primary{background:#2563EB;color:#fff}
.btn-primary:hover{background:#1D4ED8}
.btn-danger{background:#991B1B;color:#fff}
.btn-danger:hover{background:#7F1D1D}
.btn-warning{background:#92400E;color:#FDE68A}
.btn-sm{padding:4px 10px;font-size:12px}
.form-footer{padding:12px 18px;border-top:1px solid #1E2535;display:flex;gap:8px}
.alert{padding:10px 14px;border-radius:6px;font-size:13px;margin-bottom:16px}
.alert-ok{background:#022C22;border:1px solid #065F46;color:#6EE7B7}
.alert-err{background:#3B0606;border:1px solid #7F1D1D;color:#FCA5A5}
.mono{font-family:'JetBrains Mono',monospace;font-size:12px;color:#94A3B8}
.section{display:none}.section.active{display:block}
</style>
</head>
<body>

<?php if (!$isAdmin): ?>
<!-- ── LOGIN ──────────────────────────────────────────────── -->
<div class="login-wrap">
  <div class="login-box">
    <div class="fg-logo">
      <div class="fg-logo-icon">🛡</div>
      <div>
        <div style="font-size:14px;font-weight:600">FortiGate Admin</div>
        <div style="font-size:12px;color:#64748B">mermaid-mrl · 100F</div>
      </div>
    </div>
    <h2>Admin Panel</h2>
    <p>Login dengan password admin untuk mengelola user dashboard.</p>
    <?php if ($error): ?><div class="alert alert-err"><?= htmlspecialchars($error) ?></div><?php endif ?>
    <form method="POST">
      <div class="form-group" style="margin-bottom:14px">
        <label>Admin Password</label>
        <input type="password" name="admin_pass" placeholder="••••••••" autofocus required>
      </div>
      <button type="submit" name="admin_login" class="btn btn-primary" style="width:100%;justify-content:center">Masuk →</button>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ── ADMIN PANEL ─────────────────────────────────────────── -->
<div class="admin-wrap">
  <!-- Sidebar -->
  <nav class="sidebar">
    <div class="brand">
      <h3>🛡 FG Admin</h3>
      <p>mermaid-mrl</p>
    </div>
    <div class="nav-item active" onclick="showSection('users',this)">👥 Kelola User</div>
    <div class="nav-item" onclick="showSection('add',this)">➕ Tambah User</div>
    <div class="nav-item" onclick="showSection('logs',this)">📋 Activity Log</div>
    <div class="nav-item" onclick="showSection('info',this)">ℹ️ Info Sistem</div>
    <div style="margin-top:auto;padding:20px">
      <form method="POST">
        <button type="submit" name="admin_logout" class="btn btn-danger btn-sm" style="width:100%;justify-content:center">Logout</button>
      </form>
    </div>
  </nav>

  <!-- Main -->
  <main class="main">
    <div class="topbar">
      <h1>User Management</h1>
      <span style="font-size:12px;color:#64748B">FortiGate Dashboard — Admin Panel</span>
    </div>

    <?php if ($msg): ?><div class="alert alert-ok"><?= $msg ?></div><?php endif ?>
    <?php if ($error): ?><div class="alert alert-err"><?= htmlspecialchars($error) ?></div><?php endif ?>

    <!-- Stats -->
    <div class="stat-grid">
      <div class="stat-card"><div class="label">Total User</div><div class="val" style="color:#60A5FA"><?= count($users) ?></div></div>
      <div class="stat-card"><div class="label">Trial</div><div class="val trial"><?= $stats['trial'] ?? 0 ?></div></div>
      <div class="stat-card"><div class="label">Registered</div><div class="val registered"><?= $stats['registered'] ?? 0 ?></div></div>
      <div class="stat-card"><div class="label">Blocked</div><div class="val blocked"><?= $stats['blocked'] ?? 0 ?></div></div>
    </div>

    <!-- Section: User Table -->
    <div class="section active" id="sec-users">
      <div class="card">
        <div class="card-header"><h2>Daftar User</h2></div>
        <div style="overflow-x:auto">
        <table>
          <thead><tr>
            <th>ID</th><th>Username</th><th>Email</th><th>Nama</th><th>Role</th><th>Login Terakhir</th><th>Trial Exp</th><th>Devices</th><th>Aksi</th>
          </tr></thead>
          <tbody>
          <?php foreach ($users as $u): ?>
          <tr>
            <td class="mono"><?= $u['id'] ?></td>
            <td><strong><?= htmlspecialchars($u['username']) ?></strong></td>
            <td class="mono"><?= htmlspecialchars($u['email']) ?></td>
            <td><?= htmlspecialchars($u['full_name'] ?: '—') ?></td>
            <td><span class="badge badge-<?= $u['role'] ?>"><?= $u['role'] ?></span></td>
            <td class="mono"><?= $u['last_login'] ? date('d/m/y H:i', strtotime($u['last_login'])) : '—' ?></td>
            <td class="mono" style="<?= ($u['role']==='trial' && $u['trial_expires_at'] && strtotime($u['trial_expires_at'])<time()) ? 'color:#F87171' : '' ?>">
              <?= $u['trial_expires_at'] ? date('d/m/y H:i', strtotime($u['trial_expires_at'])) : '—' ?>
            </td>
            <td>
              <?php
              $dc = $db->prepare("SELECT COUNT(*) FROM fg_user_devices WHERE user_id=? AND is_active=1");
              $dc->execute([$u['id']]);
              $dcount = $dc->fetchColumn();
              $dmax = $u['max_devices'] ?? 2;
              ?>
              <span style="font-size:12px;color:<?= $dcount>=$dmax?'#F87171':'#34D399' ?>">📱 <?= $dcount ?>/<?= $dmax ?></span>
            </td>
            <td>
              <button class="btn btn-sm btn-primary" onclick="editUser(<?= htmlspecialchars(json_encode($u)) ?>)">Edit</button>
              <a class="btn btn-sm btn-warning" href="?extend=<?= $u['id'] ?>&hours=24">+24j</a>
              <a class="btn btn-sm btn-warning" href="?reset_devices=<?= $u['id'] ?>" onclick="return confirm('Reset semua device <?= htmlspecialchars($u['username']) ?>?')" title="Reset device limit">📱 Reset</a>
              <a class="btn btn-sm btn-danger" href="?delete=<?= $u['id'] ?>" onclick="return confirm('Hapus user <?= htmlspecialchars($u['username']) ?>?')">Hapus</a>
            </td>
          </tr>
          <?php endforeach ?>
          </tbody>
        </table>
        </div>
      </div>
    </div>

    <!-- Section: Add User -->
    <div class="section" id="sec-add">
      <div class="card">
        <div class="card-header"><h2>Tambah User Baru</h2></div>
        <form method="POST">
          <div class="form-grid">
            <div class="form-group"><label>Username *</label><input name="username" required placeholder="john_doe"></div>
            <div class="form-group"><label>Email *</label><input name="email" type="email" required placeholder="john@example.com"></div>
            <div class="form-group"><label>Password *</label><input name="password" type="password" required placeholder="min 8 karakter"></div>
            <div class="form-group"><label>Nama Lengkap</label><input name="full_name" placeholder="John Doe"></div>
            <div class="form-group"><label>Perusahaan</label><input name="company" placeholder="PT Contoh"></div>
            <div class="form-group"><label>Role</label>
              <select name="role">
                <option value="trial">Trial</option>
                <option value="registered">Registered</option>
                <option value="blocked">Blocked</option>
              </select>
            </div>
            <div class="form-group"><label>Durasi Trial (jam)</label><input name="trial_hours" type="number" value="24" min="1" max="720"></div>
            <div class="form-group"><label>Catatan</label><textarea name="notes" placeholder="Internal notes..."></textarea></div>
          </div>
          <div class="form-footer">
            <button type="submit" name="add_user" class="btn btn-primary">➕ Tambah User</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Section: Logs -->
    <div class="section" id="sec-logs">
      <div class="card">
        <div class="card-header"><h2>Activity Log (60 terakhir)</h2></div>
        <div style="overflow-x:auto">
        <table>
          <thead><tr><th>Waktu</th><th>User</th><th>Aksi</th><th>Detail</th><th>IP</th></tr></thead>
          <tbody>
          <?php foreach ($logs as $l): ?>
          <tr>
            <td class="mono"><?= date('d/m/y H:i:s', strtotime($l['created_at'])) ?></td>
            <td><?= htmlspecialchars($l['username'] ?? '—') ?></td>
            <td><span class="badge" style="background:#1E2535;color:#94A3B8"><?= htmlspecialchars($l['action']) ?></span></td>
            <td class="mono"><?= htmlspecialchars($l['detail']) ?></td>
            <td class="mono"><?= htmlspecialchars($l['ip_address']) ?></td>
          </tr>
          <?php endforeach ?>
          </tbody>
        </table>
        </div>
      </div>
    </div>

    <!-- Section: Info -->
    <div class="section" id="sec-info">
      <div class="card">
        <div class="card-header"><h2>Info Konfigurasi</h2></div>
        <div style="padding:16px 18px;font-size:13px;line-height:1.8;color:#94A3B8">
          <p><strong style="color:#E2E8F0">App:</strong> <?= APP_TITLE ?> v<?= APP_VERSION ?></p>
          <p><strong style="color:#E2E8F0">Trial duration:</strong> <?= TRIAL_DURATION_HOURS ?> jam</p>
          <p><strong style="color:#E2E8F0">Self-register:</strong> <?= ALLOW_SELF_REGISTER ? '✅ Aktif' : '❌ Nonaktif' ?></p>
          <p><strong style="color:#E2E8F0">URL dashboard:</strong> <a href="../index.php">../index.php</a></p>
          <p style="margin-top:16px;color:#64748B">Ubah pengaturan di <code style="background:#0F1117;padding:2px 6px;border-radius:4px">config.php</code></p>
        </div>
      </div>
    </div>
  </main>
</div>

<!-- Edit Modal -->
<div id="edit-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:100;align-items:center;justify-content:center">
  <div style="background:#1A1D26;border:1px solid #2D3748;border-radius:12px;padding:24px;width:100%;max-width:500px;max-height:90vh;overflow-y:auto">
    <h3 style="font-size:15px;font-weight:600;margin-bottom:16px">Edit User</h3>
    <form method="POST" id="edit-form">
      <input type="hidden" name="user_id" id="edit-id">
      <div style="display:grid;gap:12px">
        <div class="form-group"><label>Nama Lengkap</label><input name="full_name" id="edit-fn"></div>
        <div class="form-group"><label>Perusahaan</label><input name="company" id="edit-co"></div>
        <div class="form-group"><label>Role</label>
          <select name="role" id="edit-role">
            <option value="trial">Trial</option>
            <option value="registered">Registered</option>
            <option value="blocked">Blocked</option>
          </select>
        </div>
        <div class="form-group"><label>Perpanjang trial (jam dari sekarang)</label><input name="trial_hours" id="edit-th" type="number" value="24" min="1"></div>
        <div class="form-group"><label>Max devices (default: 2)</label><input name="max_devices" id="edit-md" type="number" value="2" min="1" max="10"></div>
        <div class="form-group"><label>Max devices</label><input name="max_devices" id="edit-md" type="number" value="2" min="1" max="10"></div>
        <div class="form-group"><label>Catatan</label><textarea name="notes" id="edit-no"></textarea></div>
      </div>
      <div style="display:flex;gap:8px;margin-top:16px">
        <button type="submit" name="update_user" class="btn btn-primary">Simpan</button>
        <button type="button" onclick="closeEdit()" class="btn" style="background:#1E2535;color:#94A3B8">Batal</button>
      </div>
    </form>
  </div>
</div>
<?php endif ?>

<script>
function showSection(id,el){
  document.querySelectorAll('.section').forEach(s=>s.classList.remove('active'));
  document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
  document.getElementById('sec-'+id).classList.add('active');
  el.classList.add('active');
}
function editUser(u){
  document.getElementById('edit-id').value=u.id;
  document.getElementById('edit-fn').value=u.full_name||'';
  document.getElementById('edit-co').value=u.company||'';
  document.getElementById('edit-role').value=u.role;
  document.getElementById('edit-no').value=u.notes||'';
  document.getElementById('edit-md').value=u.max_devices||2;
  document.getElementById('edit-modal').style.display='flex';
}
function closeEdit(){document.getElementById('edit-modal').style.display='none';}
</script>
</body>
</html>
