<?php
$pageTitle = 'Licenças MAC';
require_once __DIR__ . '/../includes/api_helpers.php';
require_once __DIR__ . '/_header.php';
$self = basename($_SERVER['PHP_SELF']);
$today = date('Y-m-d');
$csrf = gpc_csrf_token();
if (isset($_GET['export_keys']) && $_GET['export_keys'] === '1') {
    gpc_no_cache_headers();
    header('Content-Type: text/plain; charset=utf-8');
    header('Content-Disposition: attachment; filename="syntra_revenda_licencas_keys_' . date('Ymd_His') . '.txt"');
    $stmt=$db->prepare("SELECT mac_address, device_key, license_type, expire_date, key_created_at, key_expire_at, title, notes FROM devices WHERE reseller_id=:rid AND COALESCE(access_type,'app_license')='app_license' ORDER BY id DESC");
    $stmt->execute([':rid'=>$resellerId]);
    echo "SYNTRA REVENDA - BACKUP MAC + KEY\n";
    echo "Gerado em: " . date('Y-m-d H:i:s') . "\n\n";
    while($r=$stmt->fetch()){
        echo "MAC: ".($r['mac_address']??'')."\n";
        echo "KEY: ".($r['device_key']??'')."\n";
        echo "Tipo: ".(($r['license_type']??'official')==='trial'?'Teste gratis':'Licenca oficial')."\n";
        echo "Criada em: ".($r['key_created_at']??'')."\n";
        echo "Expira em: ".(($r['key_expire_at']??'') ?: ($r['expire_date']??''))."\n";
        echo "Titulo: ".($r['title']??'')."\n";
        echo "Notas: ".($r['notes']??'')."\n";
        echo "----------------------------------------\n";
    }
    exit;
}
if (!syntra_reseller_can_mac($reseller)) {
    echo '<div class="alert alert-bad">Licenças MAC estão bloqueadas para sua revenda pelo admin master.</div>';
    require_once __DIR__ . '/_footer.php';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $mac = gpc_format_mac((string)($_POST['mac_address'] ?? ''));
        $title = trim((string)($_POST['title'] ?? 'Licença MAC Revenda')) ?: 'Licença MAC Revenda';
        $expire = trim((string)($_POST['expire_date'] ?? '')) ?: date('Y-m-d', strtotime('+30 days'));
        $notes = trim((string)($_POST['notes'] ?? ''));
        $backup = isset($_POST['backup_license']) ? 1 : 0;
        $licenseType = (($_POST['license_type'] ?? 'official') === 'trial') ? 'trial' : 'official';
        if (strlen(str_replace(':','',$mac)) !== 12) {
            gpc_flash('bad', 'MAC inválido.');
        } else {
            $keyCreated = date('Y-m-d H:i:s');
            $keyExpire = $expire;
            if ($id > 0) {
                $oldKeyStmt = $db->prepare('SELECT device_key, key_created_at FROM devices WHERE id=:id AND reseller_id=:rid LIMIT 1');
                $oldKeyStmt->execute([':id'=>$id, ':rid'=>$resellerId]);
                $oldKeyRow = $oldKeyStmt->fetch();
                $key = trim((string)($oldKeyRow['device_key'] ?? '')) ?: gpc_new_device_key();
                $keyCreated = trim((string)($oldKeyRow['key_created_at'] ?? '')) ?: $keyCreated;
                if (!empty($_POST['regenerate_key'])) { $key = gpc_new_device_key(); $keyCreated = date('Y-m-d H:i:s'); }
                $stmt=$db->prepare('UPDATE devices SET mac_address=:m, title=:t, expire_date=:e, device_key=:k, license_type=:lt, key_created_at=:kc, key_expire_at=:ke, notes=:n, backup_license=:b WHERE id=:id AND reseller_id=:rid');
                $stmt->execute([':m'=>$mac, ':t'=>$title, ':e'=>$expire, ':k'=>$key, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':n'=>$notes, ':b'=>$backup, ':id'=>$id, ':rid'=>$resellerId]);
                gpc_flash('ok', 'Licença atualizada.');
            } else {
                $existingStmt = $db->prepare("SELECT id, device_key, key_created_at, license_type FROM devices WHERE reseller_id=:rid AND mac_address=:m AND COALESCE(access_type,'app_license')='app_license' ORDER BY CASE WHEN COALESCE(license_type,'official')='official' THEN 0 ELSE 1 END, id DESC LIMIT 1");
                $existingStmt->execute([':rid'=>$resellerId, ':m'=>$mac]);
                $existingRow = $existingStmt->fetch();

                if ($existingRow) {
                    $key = trim((string)($existingRow['device_key'] ?? '')) ?: gpc_new_device_key();
                    $keyCreated = trim((string)($existingRow['key_created_at'] ?? '')) ?: $keyCreated;
                    if ($licenseType === 'official' && (string)($existingRow['license_type'] ?? 'trial') === 'trial') {
                        $key = gpc_new_device_key();
                        $keyCreated = date('Y-m-d H:i:s');
                    }
                    $stmt=$db->prepare('UPDATE devices SET title=:t, expire_date=:e, device_key=:k, license_type=:lt, key_created_at=:kc, key_expire_at=:ke, notes=:n, backup_license=:b WHERE id=:id AND reseller_id=:rid');
                    $stmt->execute([':t'=>$title, ':e'=>$expire, ':k'=>$key, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':n'=>$notes, ':b'=>$backup, ':id'=>(int)$existingRow['id'], ':rid'=>$resellerId]);
                    gpc_flash('ok', 'Licença MAC já existia e foi atualizada sem consumir novo saldo.');
                } elseif ((int)$reseller['credits'] <= 0) {
                    gpc_flash('bad', 'Saldo insuficiente para criar nova Licença MAC.');
                } else {
                    $db->beginTransaction();
                    try {
                        $key = gpc_new_device_key();
                        $stmt=$db->prepare('INSERT INTO devices (mac_address, title, expire_date, device_key, license_type, key_created_at, key_expire_at, notes, access_type, reseller_id, backup_license) VALUES (:m,:t,:e,:k,:lt,:kc,:ke,:n,"app_license",:rid,:b)');
                        $stmt->execute([':m'=>$mac, ':t'=>$title, ':e'=>$expire, ':k'=>$key, ':lt'=>$licenseType, ':kc'=>$keyCreated, ':ke'=>$keyExpire, ':n'=>$notes, ':rid'=>$resellerId, ':b'=>$backup]);
                        $stmt=$db->prepare('UPDATE resellers SET credits = credits - 1 WHERE id=:id AND credits > 0');
                        $stmt->execute([':id'=>$resellerId]);
                        $db->commit();
                        gpc_flash('ok', 'Licença criada e 1 saldo consumido.');
                    } catch (Throwable $e) {
                        if ($db->inTransaction()) $db->rollBack();
                        gpc_flash('bad', 'Erro ao criar licença: ' . $e->getMessage());
                    }
                }
            }
        }
        header('Location: ' . $self); exit;
    }
}
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $db->prepare('DELETE FROM devices WHERE id=:id AND reseller_id=:rid')->execute([':id'=>(int)$_GET['delete'], ':rid'=>$resellerId]);
    gpc_flash('ok', 'Licença removida. O saldo não é devolvido automaticamente.');
    header('Location: ' . $self); exit;
}
$edit=null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt=$db->prepare('SELECT * FROM devices WHERE id=:id AND reseller_id=:rid');
    $stmt->execute([':id'=>(int)$_GET['edit'], ':rid'=>$resellerId]);
    $edit=$stmt->fetch() ?: null;
}
$q=trim((string)($_GET['q'] ?? ''));
$sql='SELECT * FROM devices WHERE reseller_id=:rid'; $params=[':rid'=>$resellerId];
if ($q !== '') { $sql.=' AND (mac_address LIKE :q OR title LIKE :q OR notes LIKE :q)'; $params[':q']='%'.$q.'%'; }
$sql.=' ORDER BY id DESC LIMIT 300';
$stmt=$db->prepare($sql); $stmt->execute($params); $rows=$stmt->fetchAll();
?>
<div class="section-title"><div><span class="eyebrow">SYNTRA Revenda</span><h2>Licenças via MAC</h2><p>Crie e acompanhe os clientes da sua revenda. Cada novo MAC consome 1 licença disponível.</p></div><span class="badge badge-ok">Saldo: <?= (int)$reseller['credits'] ?></span></div>
<div class="card"><div class="card-head"><h2><?= $edit ? 'Editar licença' : 'Nova Licença MAC' ?></h2><?php if($edit): ?><a class="btn btn-sm btn-ghost" href="<?= rv_h($self) ?>">Cancelar</a><?php endif; ?></div><div class="card-body"><form method="post"><input type="hidden" name="csrf" value="<?= rv_h($csrf) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>"><div class="form-grid"><div class="field"><label>MAC do dispositivo</label><input required name="mac_address" placeholder="AA:BB:CC:DD:EE:FF" value="<?= rv_h($edit['mac_address'] ?? '') ?>"></div><div class="field"><label>Validade</label><input type="date" name="expire_date" value="<?= rv_h($edit['expire_date'] ?? date('Y-m-d', strtotime('+30 days'))) ?>"></div><div class="field"><label>Título</label><input name="title" value="<?= rv_h($edit['title'] ?? 'Licença MAC Revenda') ?>"></div><div class="field"><label>Backup de licença</label><label class="check"><input type="checkbox" name="backup_license" <?= ((int)($edit['backup_license'] ?? 0)===1)?'checked':'' ?>> Permitir restauração de MAC</label></div><div class="field"><label>Tipo</label><select name="license_type"><option value="official" <?= (($edit['license_type'] ?? 'official') !== 'trial')?'selected':'' ?>>Licença oficial — MAC + KEY</option><option value="trial" <?= (($edit['license_type'] ?? '') === 'trial')?'selected':'' ?>>Teste grátis — só MAC</option></select></div><div class="field"><label>KEY</label><input readonly value="<?= rv_h($edit['device_key'] ?? 'Gerada ao salvar') ?>"><?php if($edit): ?><label class="check"><input type="checkbox" name="regenerate_key" value="1"> Gerar nova KEY</label><?php endif; ?></div><div class="field" style="grid-column:1/-1"><label>Notas</label><input name="notes" placeholder="Cliente, contato ou observação interna" value="<?= rv_h($edit['notes'] ?? '') ?>"></div></div><div class="form-actions"><button class="btn" type="submit"><i data-lucide="save"></i> Salvar</button></div></form></div></div>
<div class="card"><div class="card-head"><h2>Minhas licenças</h2><a class="btn btn-sm btn-ghost" href="?export_keys=1"><i data-lucide="download"></i> Exportar MAC + KEY</a></div><div class="card-body"><form method="get" class="toolbar"><input type="search" name="q" placeholder="Buscar por MAC, título ou nota" value="<?= rv_h($q) ?>"><button class="btn btn-sm" type="submit"><i data-lucide="search"></i></button></form><div class="table-scroll"><table><thead><tr><th>MAC</th><th>KEY</th><th>Título</th><th>Vence</th><th>Backup</th><th>Status</th><th></th></tr></thead><tbody><?php foreach($rows as $r): $ok=(($r['expire_date'] ?? '') >= $today); ?><tr><td><code><?= rv_h($r['mac_address']) ?></code></td><td><code><?= rv_h($r['device_key'] ?? '') ?></code><br><small><?= (($r['license_type'] ?? 'official') === 'trial') ? 'Teste' : 'Oficial' ?></small></td><td><?= rv_h($r['title']) ?></td><td><?= rv_h($r['expire_date']) ?></td><td><?= ((int)($r['backup_license'] ?? 0)===1) ? '<span class="badge badge-ok">Sim</span>' : '<span class="badge">Não</span>' ?></td><td><span class="badge <?= $ok?'badge-ok':'badge-bad' ?>"><?= $ok?'Ativa':'Vencida' ?></span></td><td class="row-actions"><a class="btn btn-sm btn-ghost btn-icon" href="?edit=<?= (int)$r['id'] ?>"><i data-lucide="pencil"></i></a><a class="btn btn-sm btn-danger btn-icon" data-confirm="Remover esta licença?" href="?delete=<?= (int)$r['id'] ?>"><i data-lucide="trash-2"></i></a></td></tr><?php endforeach; if(!$rows): ?><tr><td colspan="7" class="empty">Nenhuma licença criada.</td></tr><?php endif; ?></tbody></table></div></div></div>
<?php require_once __DIR__ . '/_footer.php'; ?>
