<?php
require_once __DIR__ . '/../includes/bootstrap.php';
admin_require_login();

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

$generated  = null;
$error      = '';
$prefillEmail = h($_GET['email'] ?? '');
$prefillBiz   = h($_GET['biz']   ?? '');
$prefillRegId = h($_GET['reg_id'] ?? '');

// View existing license files
$viewOrder = $_GET['view'] ?? '';
$viewLicense = null;
if ($viewOrder !== '') {
    $viewLicense = db_row(
        'SELECT l.*, r.business_name, r.registration_id
         FROM licenses l LEFT JOIN registrations r ON r.id = l.registration_id
         WHERE l.order_id = ?',
        [$viewOrder]
    );
}

// Generate new license
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'generate') {
    $email   = strtolower(trim($_POST['email'] ?? ''));
    $bizName = trim($_POST['business_name'] ?? '');
    $plan    = $_POST['plan'] ?? 'annual';
    $regId   = trim($_POST['registration_id'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address.';
    } elseif ($bizName === '') {
        $error = 'Business name is required.';
    } elseif (!in_array($plan, ['monthly','annual','lifetime','trial_extension'], true)) {
        $error = 'Invalid plan.';
    } else {
        // Find registration link
        $regDbId = null;
        if ($regId !== '') {
            $reg = db_row('SELECT id FROM registrations WHERE registration_id = ?', [$regId]);
            if ($reg) $regDbId = (int)$reg['id'];
        }

        $orderId         = generate_order_id();
        $registrationKey = generate_token(32);
        $hardwareKey     = generate_token(32);
        $issuedAt        = date('Y-m-d\TH:i:s');
        $expiryAt        = expiry_for_plan($plan);

        $licenseData = [
            'order_id'         => $orderId,
            'registration_key' => $registrationKey,
            'hardware_key'     => $hardwareKey,
            'business_name'    => $bizName,
            'email'            => $email,
            'plan'             => $plan,
            'issued_at'        => $issuedAt,
            'expiry'           => $expiryAt,
        ];

        try {
            $signedLicense = sign_license($licenseData);
            [$sigOk, $sigReason] = verify_license_blob($signedLicense);

            if (!$sigOk) {
                $error = 'Signature verification failed: ' . $sigReason;
            } else {
                $licenseBlob = json_encode(
                    $signedLicense,
                    JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT
                );

                db_exec(
                    'INSERT INTO licenses
                     (order_id, registration_id, email, hardware_key, registration_key,
                      license_blob, plan, expiry_at, status)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, "active")',
                    [
                        $orderId, $regDbId, $email,
                        $hardwareKey, $registrationKey,
                        $licenseBlob, $plan,
                        date('Y-m-d H:i:s', strtotime($expiryAt)),
                    ]
                );

                if ($regDbId) {
                    db_exec(
                        "UPDATE registrations SET status = 'converted' WHERE id = ?",
                        [$regDbId]
                    );
                }

                admin_log('generate_license', $orderId, "plan={$plan} email={$email}");

                $generated = [
                    'order_id'         => $orderId,
                    'registration_key' => $registrationKey,
                    'hardware_key'     => $hardwareKey,
                    'license_blob'     => $licenseBlob,
                    'expiry_at'        => $expiryAt,
                    'plan'             => $plan,
                ];
            }
        } catch (RuntimeException $e) {
            $error = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BizNode Admin — Generate License</title>
<link rel="stylesheet" href="/admin/assets/style.css">
</head>
<body>
<?php include __DIR__ . '/partials/nav.php'; ?>
<main class="main">
  <h1 class="page-title">Generate License</h1>

  <?php if ($error): ?>
    <div class="alert alert-error"><?= h($error) ?></div>
  <?php endif; ?>

  <?php if ($generated): ?>
  <!-- ── Success — show USB files ── -->
  <div class="alert alert-success">License generated successfully! Order ID: <strong><?= h($generated['order_id']) ?></strong></div>

  <div class="license-box">
    <h2 class="section-title">USB File Contents</h2>
    <p class="help-text">Copy each value to the corresponding file on the customer's USB drive.</p>

    <div class="file-block">
      <div class="file-label">📄 registration.key  <small>(write to USB root as <code>registration.key</code>)</small></div>
      <textarea class="file-content" rows="2" readonly onclick="this.select()"><?= h($generated['registration_key']) ?></textarea>
    </div>

    <div class="file-block">
      <div class="file-label">📄 hardware.key  <small>(write to USB root as <code>hardware.key</code>)</small></div>
      <textarea class="file-content" rows="2" readonly onclick="this.select()"><?= h($generated['hardware_key']) ?></textarea>
    </div>

    <div class="file-block">
      <div class="file-label">📄 .biznode_license  <small>(write to USB root as <code>.biznode_license</code>)</small></div>
      <textarea class="file-content" rows="12" readonly onclick="this.select()"><?= h($generated['license_blob']) ?></textarea>
    </div>

    <div class="meta-row">
      <span>Plan: <strong><?= h($generated['plan']) ?></strong></span>
      <span>Expires: <strong><?= h($generated['expiry_at']) ?></strong></span>
    </div>
  </div>
  <a href="/admin/generate_license.php" class="btn btn-outline" style="margin-top:1rem">Generate Another</a>

  <?php elseif ($viewLicense): ?>
  <!-- ── View existing license files ── -->
  <div class="license-box">
    <h2 class="section-title">License Files — <?= h($viewLicense['order_id']) ?></h2>
    <p class="help-text">Business: <?= h($viewLicense['business_name'] ?? $viewLicense['email']) ?> &nbsp;|&nbsp; Plan: <?= h($viewLicense['plan']) ?> &nbsp;|&nbsp; Expires: <?= h(substr($viewLicense['expiry_at'], 0, 10)) ?></p>
    <?php $blob = json_decode($viewLicense['license_blob'], true) ?? []; ?>

    <div class="file-block">
      <div class="file-label">📄 registration.key</div>
      <textarea class="file-content" rows="2" readonly onclick="this.select()"><?= h($viewLicense['registration_key']) ?></textarea>
    </div>
    <div class="file-block">
      <div class="file-label">📄 hardware.key</div>
      <textarea class="file-content" rows="2" readonly onclick="this.select()"><?= h($viewLicense['hardware_key']) ?></textarea>
    </div>
    <div class="file-block">
      <div class="file-label">📄 .biznode_license</div>
      <textarea class="file-content" rows="14" readonly onclick="this.select()"><?= h($viewLicense['license_blob']) ?></textarea>
    </div>
  </div>

  <?php else: ?>
  <!-- ── Generate form ── -->
  <form method="POST" class="form-card">
    <input type="hidden" name="action" value="generate">

    <div class="form-grid">
      <div class="form-group">
        <label class="form-label">Customer Email *</label>
        <input type="email" name="email" class="form-input" required
               value="<?= $prefillEmail ?>" placeholder="customer@example.com">
      </div>
      <div class="form-group">
        <label class="form-label">Business Name *</label>
        <input type="text" name="business_name" class="form-input" required
               value="<?= $prefillBiz ?>" placeholder="ABC Textiles Pvt Ltd">
      </div>
      <div class="form-group">
        <label class="form-label">Plan *</label>
        <select name="plan" class="form-input">
          <option value="monthly">Monthly (30 days)</option>
          <option value="annual" selected>Annual (365 days)</option>
          <option value="lifetime">Lifetime (100 years)</option>
          <option value="trial_extension">Trial Extension (30 days)</option>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Link to Registration ID <small>(optional)</small></label>
        <input type="text" name="registration_id" class="form-input"
               value="<?= $prefillRegId ?>" placeholder="REG-2026-XXXXXXX">
        <small class="help-text">Links the license to an existing trial registration.</small>
      </div>
    </div>

    <div class="alert alert-info" style="margin-top:1rem">
      <strong>After generating:</strong> The three USB file contents will be shown.
      Copy them to the customer's USB drive in the USB root folder.
      The Ed25519 signing key in <code>config.php</code> must be set correctly or signing will fail.
    </div>

    <button type="submit" class="btn btn-primary" style="margin-top:1rem">Generate License + Sign</button>
  </form>
  <?php endif; ?>

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