<?php
declare(strict_types=1);

$pageTitle = 'SYNTRA Revenda V2.0';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);
$today = date('Y-m-d');

function syntra_plan_defaults(string $plan): array {
    $plan = strtolower(trim($plan));
    if ($plan === 'business') return ['can_mac'=>1, 'can_dns'=>1, 'can_bulk_dns'=>1];
    if ($plan === 'plus') return ['can_mac'=>1, 'can_dns'=>1, 'can_bulk_dns'=>0];
    return ['can_mac'=>1, 'can_dns'=>0, 'can_bulk_dns'=>0];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'save_reseller') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim((string)($_POST['name'] ?? ''));
        $username = trim((string)($_POST['username'] ?? ''));
        $password = trim((string)($_POST['password'] ?? ''));
        $plan = strtolower(trim((string)($_POST['reseller_plan'] ?? 'basic')));
        if (!in_array($plan, ['basic','plus','business'], true)) $plan = 'basic';
        $credits = max(0, (int)($_POST['credits'] ?? 0));
        $dnsLimit = max(0, (int)($_POST['dns_limit'] ?? 0));
        $validity = trim((string)($_POST['validity'] ?? ''));
        $active = isset($_POST['active']) ? 1 : 0;
        $defs = syntra_plan_defaults($plan);
        $canMac = isset($_POST['can_mac']) ? 1 : (int)$defs['can_mac'];
        $canDns = isset($_POST['can_dns']) ? 1 : (int)$defs['can_dns'];
        $canBulkDns = isset($_POST['can_bulk_dns']) ? 1 : (int)$defs['can_bulk_dns'];
        if ($canDns === 0) { $dnsLimit = 0; $canBulkDns = 0; }
        if ($canMac === 0) { $credits = 0; }
        $notes = trim((string)($_POST['notes'] ?? ''));
        if ($name === '' || $username === '') {
            gpc_flash('bad', 'Nome e usuário são obrigatórios.');
        } else {
            try {
                if ($id > 0) {
                    if ($password !== '') {
                        $stmt = $db->prepare('UPDATE resellers SET name=:n, username=:u, password=:p, reseller_plan=:pl, credits=:c, dns_limit=:dl, validity=:v, active=:a, can_mac=:cm, can_dns=:cd, can_bulk_dns=:bd, notes=:no WHERE id=:id');
                        $stmt->execute([':n'=>$name, ':u'=>$username, ':p'=>password_hash($password, PASSWORD_DEFAULT), ':pl'=>$plan, ':c'=>$credits, ':dl'=>$dnsLimit, ':v'=>$validity, ':a'=>$active, ':cm'=>$canMac, ':cd'=>$canDns, ':bd'=>$canBulkDns, ':no'=>$notes, ':id'=>$id]);
                    } else {
                        $stmt = $db->prepare('UPDATE resellers SET name=:n, username=:u, reseller_plan=:pl, credits=:c, dns_limit=:dl, validity=:v, active=:a, can_mac=:cm, can_dns=:cd, can_bulk_dns=:bd, notes=:no WHERE id=:id');
                        $stmt->execute([':n'=>$name, ':u'=>$username, ':pl'=>$plan, ':c'=>$credits, ':dl'=>$dnsLimit, ':v'=>$validity, ':a'=>$active, ':cm'=>$canMac, ':cd'=>$canDns, ':bd'=>$canBulkDns, ':no'=>$notes, ':id'=>$id]);
                    }
                    gpc_flash('ok', 'Revendedor atualizado com permissões V2.0.');
                } else {
                    if ($password === '') { $password = '123456'; }
                    $stmt = $db->prepare('INSERT INTO resellers (name, username, password, reseller_plan, credits, dns_limit, validity, active, can_mac, can_dns, can_bulk_dns, notes) VALUES (:n,:u,:p,:pl,:c,:dl,:v,:a,:cm,:cd,:bd,:no)');
                    $stmt->execute([':n'=>$name, ':u'=>$username, ':p'=>password_hash($password, PASSWORD_DEFAULT), ':pl'=>$plan, ':c'=>$credits, ':dl'=>$dnsLimit, ':v'=>$validity, ':a'=>$active, ':cm'=>$canMac, ':cd'=>$canDns, ':bd'=>$canBulkDns, ':no'=>$notes]);
                    gpc_flash('ok', 'Revendedor cadastrado.');
                }
            } catch (Throwable $e) {
                gpc_flash('bad', 'Erro ao salvar. Verifique se o usuário já existe.');
            }
        }
        header('Location: ' . $self); exit;
    }
    if ($action === 'add_credits') {
        $id = (int)($_POST['id'] ?? 0);
        $amount = (int)($_POST['amount'] ?? 0);
        if ($id > 0 && $amount !== 0) {
            $stmt = $db->prepare('UPDATE resellers SET credits = MAX(0, credits + :q) WHERE id=:id AND COALESCE(can_mac,1)=1');
            $stmt->execute([':q'=>$amount, ':id'=>$id]);
            gpc_flash('ok', 'Saldo atualizado.');
        }
        header('Location: ' . $self); exit;
    }
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $db->prepare('SELECT (SELECT COUNT(*) FROM devices WHERE reseller_id=:id) + (SELECT COUNT(*) FROM dns_servers WHERE reseller_id=:id)');
    $stmt->execute([':id'=>$id]);
    if ((int)$stmt->fetchColumn() > 0) {
        gpc_flash('bad', 'Não é possível excluir: existem licenças ou DNS vinculadas. Desative a revenda se necessário.');
    } else {
        $db->prepare('DELETE FROM resellers WHERE id=:id')->execute([':id'=>$id]);
        gpc_flash('ok', 'Revendedor removido.');
    }
    header('Location: ' . $self); exit;
}

$edit = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $db->prepare('SELECT * FROM resellers WHERE id=:id');
    $stmt->execute([':id'=>(int)$_GET['edit']]);
    $edit = $stmt->fetch() ?: null;
}

$rows = $db->query('SELECT r.*, (SELECT COUNT(*) FROM devices d WHERE d.reseller_id=r.id) total_licenses, (SELECT COUNT(*) FROM devices d WHERE d.reseller_id=r.id AND d.expire_date >= date("now")) active_licenses, (SELECT COUNT(*) FROM dns_servers ds WHERE ds.reseller_id=r.id) total_dns, (SELECT COUNT(*) FROM dns_servers ds WHERE ds.reseller_id=r.id AND ds.status=1) active_dns FROM resellers r ORDER BY id DESC')->fetchAll();
$total = count($rows); $active = 0; $credits = 0; $basic=0; $plus=0; $business=0;
foreach ($rows as $r) {
    if (syntra_reseller_is_valid($r)) $active++;
    $credits += (int)$r['credits'];
    $pl = strtolower((string)($r['reseller_plan'] ?? 'basic'));
    if ($pl === 'business') $business++; elseif ($pl === 'plus') $plus++; else $basic++;
}
$csrf = gpc_csrf_token();
$planEdit = strtolower((string)($edit['reseller_plan'] ?? 'basic'));
?>
<div class="section-title">
  <div><span class="eyebrow">SYNTRA Revenda V2.0</span><h2>Gestão profissional de revendas</h2><p>Separe revendas por plano, defina se cada uma usa Licença MAC, Código Parceiro/SYNTRA ID ou ambos, e mantenha o admin master no controle total.</p></div>
  <a class="btn btn-ghost" href="revenda/index.php" target="_blank"><i data-lucide="external-link"></i> Abrir painel revenda</a>
</div>
<div class="stats stats-compact">
  <div class="stat stat-accent"><div class="stat-label">Revendedores</div><div class="stat-value"><?= $total ?></div><div class="stat-hint"><?= $active ?> ativos</div></div>
  <div class="stat"><div class="stat-label">Planos</div><div class="stat-value" style="font-size:22px">B<?= $basic ?> / P<?= $plus ?> / Biz<?= $business ?></div><div class="stat-hint">Basic, Plus e Business</div></div>
  <div class="stat stat-purple"><div class="stat-label">Licenças MAC</div><div class="stat-value"><?= $credits ?></div><div class="stat-hint">Saldo liberado pelo admin</div></div>
  <div class="stat stat-green"><div class="stat-label">Controle</div><div class="stat-value" style="font-size:22px">Admin</div><div class="stat-hint">MAC, DNS ou ambos por revenda</div></div>
</div>
<div class="card"><div class="card-head"><h2><?= $edit ? 'Editar revendedor' : 'Novo revendedor' ?></h2><?php if($edit): ?><a href="<?= gpc_h($self) ?>" class="btn btn-sm btn-ghost">Cancelar</a><?php endif; ?></div><div class="card-body">
<form method="post"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="save_reseller"><input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
<div class="form-grid">
 <div class="field"><label>Nome / Marca</label><input required name="name" value="<?= gpc_h($edit['name'] ?? '') ?>" placeholder="Ex: Revenda João"></div>
 <div class="field"><label>Usuário</label><input required name="username" value="<?= gpc_h($edit['username'] ?? '') ?>" placeholder="usuario_revenda"></div>
 <div class="field"><label>Senha <?= $edit ? '(deixe vazio para manter)' : '' ?></label><input type="text" name="password" placeholder="<?= $edit ? 'Manter senha atual' : '123456' ?>"></div>
 <div class="field"><label>Nível da revenda</label><select name="reseller_plan"><option value="basic" <?= $planEdit==='basic'?'selected':'' ?>>BASIC — somente MAC</option><option value="plus" <?= $planEdit==='plus'?'selected':'' ?>>PLUS — MAC + DNS</option><option value="business" <?= $planEdit==='business'?'selected':'' ?>>BUSINESS — painel completo</option></select><small>O plano ajuda a vender e organizar permissões.</small></div>
 <div class="field"><label>Licenças MAC disponíveis</label><input type="number" min="0" name="credits" value="<?= gpc_h((string)($edit['credits'] ?? 0)) ?>"></div>
 <div class="field"><label>Limite de Código Parceiro / DNS</label><input type="number" min="0" name="dns_limit" value="<?= gpc_h((string)($edit['dns_limit'] ?? 0)) ?>"><small>Use 0 para bloquear DNS/SYNTRA ID nesta revenda.</small></div>
 <div class="field"><label>Validade do painel revenda</label><input type="date" name="validity" value="<?= gpc_h($edit['validity'] ?? '') ?>"><small>Vencido = revenda não entra e códigos ficam inativos.</small></div>
 <div class="field"><label>Status</label><label class="check"><input type="checkbox" name="active" <?= ((int)($edit['active'] ?? 1) === 1) ? 'checked' : '' ?>> Revendedor ativo</label></div>
 <div class="field"><label>Permissões V2.0</label><label class="check"><input type="checkbox" name="can_mac" <?= ((int)($edit['can_mac'] ?? 1) === 1) ? 'checked' : '' ?>> Vender Licença MAC</label><label class="check"><input type="checkbox" name="can_dns" <?= ((int)($edit['can_dns'] ?? 0) === 1) ? 'checked' : '' ?>> Usar Código Parceiro / DNS</label><label class="check"><input type="checkbox" name="can_bulk_dns" <?= ((int)($edit['can_bulk_dns'] ?? 0) === 1) ? 'checked' : '' ?>> Troca em massa</label></div>
 <div class="field" style="grid-column:1/-1"><label>Notas internas</label><input name="notes" value="<?= gpc_h($edit['notes'] ?? '') ?>" placeholder="Observações do admin"></div>
</div><div class="form-actions"><button class="btn" type="submit"><i data-lucide="save"></i> Salvar revendedor</button></div></form>
</div></div>
<div class="card"><div class="card-head"><h2>Revendedores cadastrados</h2></div><div class="card-body"><div class="table-scroll"><table><thead><tr><th>Revenda</th><th>Plano</th><th>Permissões</th><th>Saldo</th><th>Licenças</th><th>Códigos/DNS</th><th>Validade</th><th>Status</th><th>Saldo</th><th></th></tr></thead><tbody>
<?php foreach($rows as $r): $rvOk=syntra_reseller_is_valid($r); $plan=syntra_reseller_plan_label((string)($r['reseller_plan'] ?? 'basic')); ?>
<tr><td><strong><?= gpc_h($r['name']) ?></strong><br><code><?= gpc_h($r['username']) ?></code></td><td><span class="badge badge-purple"><?= gpc_h($plan) ?></span></td><td><span class="badge <?= ((int)($r['can_mac'] ?? 1)===1)?'badge-ok':'badge-bad' ?>">MAC</span> <span class="badge <?= ((int)($r['can_dns'] ?? 0)===1)?'badge-ok':'badge-bad' ?>">SYNTRA ID</span> <span class="badge <?= ((int)($r['can_bulk_dns'] ?? 0)===1)?'badge-ok':'badge-bad' ?>">Massa</span></td><td><span class="badge badge-ok"><?= (int)$r['credits'] ?> MAC</span></td><td><?= (int)$r['active_licenses'] ?> ativas / <?= (int)$r['total_licenses'] ?> total</td><td><?= (int)$r['total_dns'] ?> / <?= (int)($r['dns_limit'] ?? 0) ?></td><td><?= gpc_h($r['validity'] ?: 'Sem vencimento') ?></td><td><span class="badge <?= $rvOk?'badge-ok':'badge-bad' ?>"><?= $rvOk?'Ativo':'Bloqueado/Vencido' ?></span></td><td><form method="post" class="toolbar"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="add_credits"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><input type="number" name="amount" placeholder="+10 ou -1"><button class="btn btn-sm" type="submit">Aplicar</button></form></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="Excluir revendedor?" href="?delete=<?= (int)$r['id'] ?>"><i data-lucide="trash-2"></i></a></td></tr>
<?php endforeach; if(!$rows): ?><tr><td colspan="10" class="empty">Nenhum revendedor cadastrado</td></tr><?php endif; ?>
</tbody></table></div></div></div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
