<?php
require_once __DIR__ . '/_db.php';

$pdo = db();
$id  = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: index.php'); exit; }

$customer = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
$customer->execute([$id]);
$customer = $customer->fetch();
if (!$customer) { header('Location: index.php'); exit; }

$msg_key   = $_GET['msg'] ?? '';
$install_token_show = '';
if ($msg_key === 'saved')       $msg = 'Cadastro atualizado com sucesso.';
elseif ($msg_key === 'created') $msg = 'Cliente cadastrado com sucesso.';
elseif ($msg_key === 'lic_gen') $msg = 'Nova licença gerada com sucesso.';
elseif ($msg_key === 'lic_rev') $msg = 'Licença atualizada.';
elseif ($msg_key === 'token_gen') {
    $install_token_show = $_GET['token'] ?? '';
    $msg = 'Token de instalação gerado. Válido por 48h. Copie agora — não será exibido novamente.';
}
else $msg = '';

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

    // Gerar nova licença
    if ($action === 'generate') {
        $days       = max(1, min(3650, (int)($_POST['days'] ?? LICENSE_DEFAULT_DAYS)));
        $notes      = trim($_POST['notes'] ?? '');
        $expires    = date('Y-m-d', strtotime("+{$days} days"));
        $key        = generate_key();
        $api_secret = generate_api_secret();
        $pdo->prepare("INSERT INTO licenses (license_key, customer_id, api_secret, expires_at, notes) VALUES (?,?,?,?,?)")
            ->execute([$key, $id, $api_secret, $expires, $notes]);
        header('Location: customer_view.php?id=' . $id . '&msg=lic_gen'); exit;
    }

    // Gerar token de instalação (uso único, válido por 48h)
    if ($action === 'gen_token') {
        $lic_id = (int)$_POST['lic_id'];
        $token  = generate_install_token();
        $expires = date('Y-m-d H:i:s', strtotime('+48 hours'));
        $pdo->prepare("UPDATE licenses SET install_token = ?, install_token_expires_at = ? WHERE id = ? AND customer_id = ?")
            ->execute([$token, $expires, $lic_id, $id]);
        header('Location: customer_view.php?id=' . $id . '&msg=token_gen&token=' . $token); exit;
    }

    // Renovar validade
    if ($action === 'renew') {
        $lic_id  = (int)$_POST['lic_id'];
        $expires = $_POST['expires'] ?? '';
        if ($expires && preg_match('/^\d{4}-\d{2}-\d{2}$/', $expires)) {
            $pdo->prepare("UPDATE licenses SET expires_at=? WHERE id=? AND customer_id=?")
                ->execute([$expires, $lic_id, $id]);
        }
        header('Location: customer_view.php?id=' . $id . '&msg=lic_rev'); exit;
    }

    // Revogar / Reativar (agora via POST, não GET)
    if ($action === 'toggle_lic') {
        $lic_id = (int)$_POST['lic_id'];
        $pdo->prepare("UPDATE licenses SET active = NOT active WHERE id=? AND customer_id=?")->execute([$lic_id, $id]);
        header('Location: customer_view.php?id=' . $id); exit;
    }

    // Resetar hardware_id (agora via POST, não GET)
    if ($action === 'reset_hw') {
        $lic_id = (int)$_POST['lic_id'];
        $pdo->prepare("UPDATE licenses SET hardware_id=NULL, activated_at=NULL WHERE id=? AND customer_id=?")->execute([$lic_id, $id]);
        header('Location: customer_view.php?id=' . $id . '&msg=lic_rev'); exit;
    }
}

$licenses = $pdo->prepare("SELECT * FROM licenses WHERE customer_id = ? ORDER BY created_at DESC");
$licenses->execute([$id]);
$licenses = $licenses->fetchAll();

$page_title  = $customer['name'];
$current_nav = 'customers';
require __DIR__ . '/_layout.php';
?>

<div style="margin-bottom:1rem"><a href="index.php">← Clientes</a></div>

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

<?php if ($install_token_show): ?>
<div class="card" style="border:2px solid #f59e0b;background:#1a1200">
  <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:.75rem">
    <span style="font-size:1.3rem">⚠️</span>
    <strong style="color:#f59e0b">Token de Instalação — copie agora, não será exibido novamente</strong>
  </div>
  <code style="display:block;background:#0f0f0f;padding:.75rem 1rem;border-radius:6px;font-size:.9rem;
               word-break:break-all;color:#facc15;letter-spacing:.05em;user-select:all">
    <?= h($install_token_show) ?>
  </code>
  <p style="margin-top:.75rem;font-size:.82rem;color:#94a3b8">
    Passe este token ao cliente. Ele deve colocar em <code>INSTALL_TOKEN</code> no <code>install.conf</code>.<br>
    Válido por 48h · Uso único · A chave de licença e o segredo serão buscados automaticamente na instalação.
  </p>
</div>
<?php endif; ?>

<!-- Cabeçalho do cliente -->
<div class="card" style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:1rem">
  <div>
    <h1 style="margin-bottom:.3rem"><?= h($customer['name']) ?>
      <?php if (!$customer['active']): ?><span class="badge badge-revoked" style="font-size:.75rem">Inativo</span><?php endif; ?>
    </h1>
    <div style="color:#94a3b8;font-size:.9rem;display:flex;flex-wrap:wrap;gap:1rem;margin-top:.4rem">
      <span>✉️ <?= h($customer['email']) ?></span>
      <?php if ($customer['company']): ?><span>🏢 <?= h($customer['company']) ?></span><?php endif; ?>
      <?php if ($customer['phone']): ?><span>📱 <?= h($customer['phone']) ?></span><?php endif; ?>
      <span style="color:#475569">Desde <?= date('d/m/Y', strtotime($customer['created_at'])) ?></span>
    </div>
    <?php if ($customer['notes']): ?>
      <p style="margin-top:.6rem;font-size:.85rem;color:#64748b"><?= nl2br(h($customer['notes'])) ?></p>
    <?php endif; ?>
  </div>
  <a href="customer_form.php?id=<?= $id ?>" class="btn btn-gray">Editar Cadastro</a>
</div>

<!-- Gerar nova licença -->
<div class="card">
  <h2>Gerar Nova Licença</h2>
  <form method="post" style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:flex-end">
    <?= csrf_field() ?>
    <input type="hidden" name="action" value="generate">
    <div>
      <label>Validade (dias)</label>
      <input type="number" name="days" value="<?= LICENSE_DEFAULT_DAYS ?>" min="1" max="3650" style="width:120px">
    </div>
    <div style="flex:1;min-width:180px">
      <label>Observação (opcional)</label>
      <input type="text" name="notes" placeholder="Ex: Renovação mensal" maxlength="200">
    </div>
    <button type="submit" class="btn btn-green">Gerar Licença</button>
  </form>
</div>

<!-- Lista de licenças -->
<div class="card" style="padding:0;overflow:hidden">
<div style="padding:1rem 1.25rem;border-bottom:1px solid #334155">
  <h2 style="margin:0">Licenças (<?= count($licenses) ?>)</h2>
</div>
<?php if (empty($licenses)): ?>
  <p class="empty">Nenhuma licença gerada ainda.</p>
<?php else: ?>
<table>
  <thead>
    <tr>
      <th>Chave</th><th>Status</th><th>Validade</th>
      <th>Ativada em</th><th>Última Verificação</th><th>Hardware ID</th><th>Obs.</th><th>Ações</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($licenses as $lic): ?>
  <tr>
    <td><span class="key"><?= h($lic['license_key']) ?></span></td>
    <td><?= license_badge($lic) ?></td>
    <td>
      <?= date('d/m/Y', strtotime($lic['expires_at'])) ?>
      <form method="post" style="display:flex;gap:.3rem;margin-top:.3rem">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="renew">
        <input type="hidden" name="lic_id" value="<?= $lic['id'] ?>">
        <input type="date" name="expires" value="<?= $lic['expires_at'] ?>" style="width:130px;padding:.2rem .4rem;font-size:.78rem">
        <button type="submit" class="btn btn-green btn-sm">OK</button>
      </form>
    </td>
    <td><?= $lic['activated_at'] ? date('d/m/Y H:i', strtotime($lic['activated_at'])) : '—' ?></td>
    <td><?= $lic['last_check_at'] ? date('d/m/Y H:i', strtotime($lic['last_check_at'])) : '—' ?></td>
    <td style="font-family:monospace;font-size:.72rem;max-width:110px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
        title="<?= h($lic['hardware_id'] ?? '') ?>">
      <?= $lic['hardware_id'] ? h(substr($lic['hardware_id'], 0, 16)) . '…' : '—' ?>
    </td>
    <td style="font-size:.78rem;color:#64748b;max-width:120px"><?= h($lic['notes'] ?? '') ?></td>
    <td style="white-space:nowrap">
      <!-- Revogar/Reativar via POST -->
      <form method="post" style="display:inline-block">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="toggle_lic">
        <input type="hidden" name="lic_id" value="<?= $lic['id'] ?>">
        <button type="submit" class="btn btn-sm <?= $lic['active'] ? 'btn-gray' : 'btn-green' ?>">
          <?= $lic['active'] ? 'Revogar' : 'Reativar' ?>
        </button>
      </form>
      <?php if ($lic['hardware_id']): ?>
      <!-- Reset HW via POST -->
      <form method="post" style="display:inline-block"
            onsubmit="return confirm('Resetar Hardware ID? O cliente poderá ativar em outra máquina.')">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="reset_hw">
        <input type="hidden" name="lic_id" value="<?= $lic['id'] ?>">
        <button type="submit" class="btn btn-gray btn-sm">Reset HW</button>
      </form>
      <?php endif; ?>
      <!-- Gerar token de instalação (uso único 48h) -->
      <form method="post" style="display:inline-block"
            onsubmit="return confirm('Gerar token de instalação para esta licença?\nO token anterior será invalidado.')">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="gen_token">
        <input type="hidden" name="lic_id" value="<?= $lic['id'] ?>">
        <button type="submit" class="btn btn-sm" style="background:#7c3aed;color:#fff">Token</button>
      </form>
      <a href="logs.php?key=<?= urlencode($lic['license_key']) ?>" class="btn btn-blue btn-sm">Logs</a>
    </td>
  </tr>
  <?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>
</div>

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