<?php
require __DIR__ . '/auth.php';
requireLogin();

$pdo = db();
$notice = '';
$newKey = '';

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

    if ($action === 'create') {
        $name    = trim($_POST['customer_name'] ?? '');
        $email   = trim($_POST['customer_email'] ?? '');
        $notes   = trim($_POST['notes'] ?? '');
        $max     = max(1, (int) ($_POST['max_activations'] ?? 1));
        $days    = (int) ($_POST['expires_days'] ?? 0);
        $expires = $days > 0 ? date('Y-m-d H:i:s', strtotime("+$days days")) : null;
        $features = isset($_POST['features']) && is_array($_POST['features'])
            ? implode(',', array_intersect($_POST['features'], array_keys(ALL_FEATURES)))
            : implode(',', array_keys(ALL_FEATURES)); // default: all features

        $key = generateLicenseKey();
        $stmt = $pdo->prepare('INSERT INTO licenses (license_key, customer_name, customer_email, features, max_activations, status, expires_at, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([$key, $name, $email, $features, $max, 'active', $expires, $notes]);
        $newKey = $key;
        $notice = 'License created.';
    }

    if ($action === 'toggle' && !empty($_POST['id'])) {
        $stmt = $pdo->prepare('SELECT status FROM licenses WHERE id = ?');
        $stmt->execute([$_POST['id']]);
        $row = $stmt->fetch();
        if ($row) {
            $newStatus = $row['status'] === 'active' ? 'disabled' : 'active';
            $stmt = $pdo->prepare('UPDATE licenses SET status = ? WHERE id = ?');
            $stmt->execute([$newStatus, $_POST['id']]);
            $notice = $newStatus === 'active' ? 'License activated.' : 'License deactivated. It will stop working next time the app checks in.';
        }
    }

    if ($action === 'update' && !empty($_POST['id'])) {
        $name  = trim($_POST['customer_name'] ?? '');
        $email = trim($_POST['customer_email'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        $max   = max(1, (int) ($_POST['max_activations'] ?? 1));
        $expiresRaw = trim($_POST['expires_at'] ?? '');
        $expires = $expiresRaw !== '' ? date('Y-m-d H:i:s', strtotime($expiresRaw)) : null;
        $features = isset($_POST['features']) && is_array($_POST['features'])
            ? implode(',', array_intersect($_POST['features'], array_keys(ALL_FEATURES)))
            : '';

        $stmt = $pdo->prepare('UPDATE licenses SET customer_name=?, customer_email=?, features=?, max_activations=?, expires_at=?, notes=? WHERE id=?');
        $stmt->execute([$name, $email, $features, $max, $expires, $notes, $_POST['id']]);
        $notice = 'License updated.';
    }

    if ($action === 'delete' && !empty($_POST['id'])) {
        $stmt = $pdo->prepare('DELETE FROM licenses WHERE id = ?');
        $stmt->execute([$_POST['id']]);
        $notice = 'License deleted.';
    }

    if ($action === 'revoke_device' && !empty($_POST['activation_id'])) {
        $stmt = $pdo->prepare('DELETE FROM activations WHERE id = ?');
        $stmt->execute([$_POST['activation_id']]);
        $notice = 'Device revoked. That machine will be locked out next check-in.';
    }
}

$licenses = $pdo->query('SELECT * FROM licenses ORDER BY created_at DESC')->fetchAll();

$activationsByLicense = [];
$countStmt = $pdo->query('SELECT * FROM activations ORDER BY last_seen_at DESC');
foreach ($countStmt->fetchAll() as $a) {
    $activationsByLicense[$a['license_id']][] = $a;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>License Admin</title>
<style>
  :root{--brand:#6dc82c;--bg:#0f1115;--card:#171a21;--card2:#12141a;--border:#262b36;--text:#e7e9ee;--text2:#9aa3b2;--red:#f87171;--amber:#fbbf24;}
  *{box-sizing:border-box;}
  body{margin:0;background:var(--bg);color:var(--text);font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;font-size:14px;}
  header{display:flex;align-items:center;justify-content:space-between;padding:18px 28px;border-bottom:1px solid var(--border);background:var(--card2);}
  header h1{font-size:16px;margin:0;}
  nav{display:flex;gap:18px;align-items:center;}
  nav a{color:var(--text2);text-decoration:none;font-size:13px;}
  nav a.active{color:var(--text);font-weight:600;}
  nav a:hover{color:var(--text);}
  main{max-width:1100px;margin:0 auto;padding:28px;}
  .notice{background:rgba(109,200,44,.12);border:1px solid rgba(109,200,44,.35);color:var(--brand);padding:10px 14px;border-radius:8px;margin-bottom:20px;}
  .newkey{background:rgba(109,200,44,.08);border:1px dashed var(--brand);border-radius:10px;padding:16px;margin-bottom:20px;}
  .newkey code{display:block;font-size:16px;font-family:'DM Mono',monospace;margin-top:6px;user-select:all;color:var(--text);}
  .card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:20px;margin-bottom:24px;}
  .card h2{font-size:14px;margin:0 0 16px;text-transform:uppercase;letter-spacing:.04em;color:var(--text2);}
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px 16px;}
  label{display:block;font-size:11px;color:var(--text2);margin-bottom:5px;font-weight:600;text-transform:uppercase;letter-spacing:.03em;}
  input[type=text],input[type=email],input[type=number],input[type=date],textarea{width:100%;padding:9px 10px;border-radius:7px;border:1px solid var(--border);background:#0d0f14;color:var(--text);font-size:13px;}
  input:focus,textarea:focus{outline:none;border-color:var(--brand);}
  .features{display:flex;flex-wrap:wrap;gap:8px;grid-column:1/-1;}
  .features label{display:flex;align-items:center;gap:6px;background:#0d0f14;border:1px solid var(--border);padding:6px 10px;border-radius:20px;font-size:12px;text-transform:none;font-weight:500;color:var(--text);cursor:pointer;}
  .features input{width:auto;margin:0;}
  .full{grid-column:1/-1;}
  button, .btn{border:0;border-radius:7px;padding:8px 14px;font-weight:600;font-size:12px;cursor:pointer;}
  .btn-primary{background:var(--brand);color:#0b1200;}
  .btn-primary:hover{filter:brightness(1.08);}
  .btn-ghost{background:transparent;border:1px solid var(--border);color:var(--text2);}
  .btn-ghost:hover{color:var(--text);border-color:var(--text2);}
  .btn-danger{background:transparent;border:1px solid rgba(248,113,113,.4);color:var(--red);}
  .btn-danger:hover{background:rgba(248,113,113,.1);}
  table{width:100%;border-collapse:collapse;}
  th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.03em;color:var(--text2);padding:8px 10px;border-bottom:1px solid var(--border);}
  td{padding:10px;border-bottom:1px solid var(--border);vertical-align:top;font-size:13px;}
  tr:last-child td{border-bottom:none;}
  .badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:11px;font-weight:700;}
  .badge-active{background:rgba(109,200,44,.15);color:var(--brand);}
  .badge-disabled{background:rgba(248,113,113,.15);color:var(--red);}
  .badge-expired{background:rgba(251,191,36,.15);color:var(--amber);}
  .key{font-family:monospace;font-size:12px;color:var(--text2);word-break:break-all;}
  .muted{color:var(--text2);font-size:12px;}
  .devices{margin-top:8px;padding-left:0;list-style:none;}
  .devices li{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 0;border-bottom:1px dashed var(--border);font-size:12px;}
  .devices li:last-child{border-bottom:none;}
  .actions{display:flex;gap:6px;flex-wrap:wrap;}
  details summary{cursor:pointer;color:var(--text2);font-size:12px;}
  form.inline{display:inline;}
  .edit-row td{background:var(--card2);padding-top:16px;padding-bottom:16px;}
  .edit-row .grid{margin-bottom:12px;}
  .edit-toggle{background:transparent;border:1px solid var(--border);color:var(--text2);}
  .edit-toggle:hover{color:var(--text);border-color:var(--text2);}
</style>
<script>
  function toggleEdit(id) {
    var row = document.getElementById('edit-' + id);
    if (row) row.style.display = (row.style.display === 'none' || !row.style.display) ? 'table-row' : 'none';
  }
</script>
</head>
<body>
<header>
  <h1>License Admin</h1>
  <nav>
    <a href="index.php" class="active">Licenses</a>
    <a href="notifications.php">Notifications</a>
    <a href="logout.php">Logout</a>
  </nav>
</header>
<main>

  <?php if ($notice): ?><div class="notice"><?= e($notice) ?></div><?php endif; ?>

  <?php if ($newKey): ?>
    <div class="newkey">
      <span class="muted">New license key — copy and send this to the customer:</span>
      <code><?= e($newKey) ?></code>
    </div>
  <?php endif; ?>

  <div class="card">
    <h2>Create License</h2>
    <form method="post">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="create">
      <div class="grid">
        <div>
          <label>Customer Name</label>
          <input type="text" name="customer_name" placeholder="Optional">
        </div>
        <div>
          <label>Customer Email</label>
          <input type="email" name="customer_email" placeholder="Optional">
        </div>
        <div>
          <label>Max Activations (devices)</label>
          <input type="number" name="max_activations" value="1" min="1">
        </div>
        <div>
          <label>Expires In (days, 0 = lifetime)</label>
          <input type="number" name="expires_days" value="0" min="0">
        </div>
        <div class="full">
          <label>Features Included</label>
          <div class="features">
            <?php foreach (ALL_FEATURES as $id => $lbl): ?>
              <label><input type="checkbox" name="features[]" value="<?= e($id) ?>" checked> <?= e($lbl) ?></label>
            <?php endforeach; ?>
          </div>
        </div>
        <div class="full">
          <label>Notes</label>
          <textarea name="notes" rows="2" placeholder="Optional internal notes"></textarea>
        </div>
      </div>
      <br>
      <button class="btn-primary" type="submit">Generate License</button>
    </form>
  </div>

  <div class="card">
    <h2>All Licenses (<?= count($licenses) ?>)</h2>
    <table>
      <thead>
        <tr>
          <th>Key / Customer</th>
          <th>Status</th>
          <th>Features</th>
          <th>Devices</th>
          <th>Expires</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($licenses as $lic):
          $isExpired = $lic['expires_at'] && strtotime($lic['expires_at']) < time();
          $devices = $activationsByLicense[$lic['id']] ?? [];
          $featureList = array_filter(explode(',', $lic['features']));
        ?>
        <tr>
          <td>
            <div class="key"><?= e($lic['license_key']) ?></div>
            <?php if ($lic['customer_name'] || $lic['customer_email']): ?>
              <div class="muted"><?= e($lic['customer_name']) ?> <?= $lic['customer_email'] ? '· ' . e($lic['customer_email']) : '' ?></div>
            <?php endif; ?>
            <?php if ($lic['notes']): ?><div class="muted"><?= e($lic['notes']) ?></div><?php endif; ?>
          </td>
          <td>
            <?php if ($isExpired): ?>
              <span class="badge badge-expired">Expired</span>
            <?php elseif ($lic['status'] === 'active'): ?>
              <span class="badge badge-active">Active</span>
            <?php else: ?>
              <span class="badge badge-disabled">Disabled</span>
            <?php endif; ?>
          </td>
          <td class="muted"><?= count($featureList) === count(ALL_FEATURES) ? 'All features' : e(implode(', ', $featureList)) ?></td>
          <td>
            <?= count($devices) ?> / <?= (int) $lic['max_activations'] ?>
            <?php if ($devices): ?>
            <details>
              <summary>view</summary>
              <ul class="devices">
                <?php foreach ($devices as $d): ?>
                  <li>
                    <span title="<?= e($d['machine_id']) ?>"><?= e(substr($d['machine_id'], 0, 12)) ?>… <span class="muted">(<?= e($d['last_seen_at']) ?>)</span></span>
                    <form class="inline" method="post" onsubmit="return confirm('Revoke this device?');">
                      <?= csrfField() ?>
                      <input type="hidden" name="action" value="revoke_device">
                      <input type="hidden" name="activation_id" value="<?= (int) $d['id'] ?>">
                      <button class="btn-danger" type="submit">Revoke</button>
                    </form>
                  </li>
                <?php endforeach; ?>
              </ul>
            </details>
            <?php endif; ?>
          </td>
          <td class="muted"><?= $lic['expires_at'] ? e($lic['expires_at']) : 'Lifetime' ?></td>
          <td>
            <div class="actions">
              <button type="button" class="edit-toggle" onclick="toggleEdit(<?= (int) $lic['id'] ?>)">Edit</button>
              <form class="inline" method="post">
                <?= csrfField() ?>
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= (int) $lic['id'] ?>">
                <button class="<?= $lic['status'] === 'active' ? 'btn-danger' : 'btn-primary' ?>" type="submit">
                  <?= $lic['status'] === 'active' ? 'Deactivate' : 'Activate' ?>
                </button>
              </form>
              <form class="inline" method="post" onsubmit="return confirm('Delete this license permanently?');">
                <?= csrfField() ?>
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int) $lic['id'] ?>">
                <button class="btn-ghost" type="submit">Delete</button>
              </form>
            </div>
          </td>
        </tr>
        <tr class="edit-row" id="edit-<?= (int) $lic['id'] ?>" style="display:none;">
          <td colspan="6">
            <form method="post">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="id" value="<?= (int) $lic['id'] ?>">
              <div class="grid">
                <div>
                  <label>Customer Name</label>
                  <input type="text" name="customer_name" value="<?= e($lic['customer_name']) ?>" placeholder="Optional">
                </div>
                <div>
                  <label>Customer Email</label>
                  <input type="email" name="customer_email" value="<?= e($lic['customer_email']) ?>" placeholder="Optional">
                </div>
                <div>
                  <label>Max Activations (devices)</label>
                  <input type="number" name="max_activations" value="<?= (int) $lic['max_activations'] ?>" min="1">
                </div>
                <div>
                  <label>Expires At (blank = lifetime)</label>
                  <input type="text" name="expires_at" value="<?= e($lic['expires_at'] ?? '') ?>" placeholder="YYYY-MM-DD or blank">
                </div>
                <div class="full">
                  <label>Features Included</label>
                  <div class="features">
                    <?php foreach (ALL_FEATURES as $fid => $flbl): ?>
                      <label><input type="checkbox" name="features[]" value="<?= e($fid) ?>" <?= in_array($fid, $featureList, true) ? 'checked' : '' ?>> <?= e($flbl) ?></label>
                    <?php endforeach; ?>
                  </div>
                </div>
                <div class="full">
                  <label>Notes</label>
                  <textarea name="notes" rows="2" placeholder="Optional internal notes"><?= e($lic['notes']) ?></textarea>
                </div>
              </div>
              <br>
              <button class="btn-primary" type="submit">Save Changes</button>
              <button type="button" class="btn-ghost" onclick="toggleEdit(<?= (int) $lic['id'] ?>)">Cancel</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$licenses): ?>
          <tr><td colspan="6" class="muted">No licenses yet — create one above.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

</main>
</body>
</html>
