<?php
require_once dirname(__DIR__) . "/includes/auth.php";
require_once dirname(__DIR__) . "/includes/revenda_schema.php";

revenda_ensure_schema($db);

function dns_clean_url(string $url): string {
    $url = trim($url);
    if ($url !== '' && !preg_match('~^https?://~i', $url)) {
        $url = 'http://' . $url;
    }
    return rtrim($url, '/');
}

$msg = '';
$msgType = 'success';

if (isset($_POST["submit"])) {
    $nome = trim((string)($_POST["nome"] ?? ''));
    $url = dns_clean_url((string)($_POST["url"] ?? ''));

    if ($nome !== '' && $url !== '') {
        if ($isRev) {
            $stmt = $db->prepare("INSERT OR REPLACE INTO revendedor_dns (revendedor_id, nome, url, updated_at) VALUES (?, ?, ?, strftime('%s','now'))");
            $stmt->execute([$revId, $nome, $url]);
        } else {
            $stmt = $db->prepare("INSERT OR REPLACE INTO dns (nome, url) VALUES (?, ?)");
            $stmt->execute([$nome, $url]);
        }
        header("Location: dns.php?r=adicionado");
        exit;
    }
    $msg = 'Informe nome e DNS.';
    $msgType = 'danger';
}

if (isset($_POST["submitU"])) {
    $nome = trim((string)($_POST["nome"] ?? ''));
    $url = dns_clean_url((string)($_POST["url"] ?? ''));

    if ($nome !== '' && $url !== '') {
        if ($isRev) {
            $id = (int)($_GET["update"] ?? 0);
            $stmt = $db->prepare("UPDATE revendedor_dns SET nome=?, url=?, updated_at=strftime('%s','now') WHERE id=? AND revendedor_id=?");
            $stmt->execute([$nome, $url, $id, $revId]);
        } else {
            $old = trim((string)($_GET["update"] ?? ''));
            $stmt = $db->prepare("UPDATE dns SET nome=?, url=? WHERE nome=?");
            $stmt->execute([$nome, $url, $old]);
        }
        header("Location: dns.php?r=atualizado");
        exit;
    }
    $msg = 'Informe nome e DNS.';
    $msgType = 'danger';
}

if (isset($_GET["delete"])) {
    if ($isRev) {
        $id = (int)$_GET["delete"];
        $stmt = $db->prepare("DELETE FROM revendedor_dns WHERE id=? AND revendedor_id=?");
        $stmt->execute([$id, $revId]);
    } else {
        $stmt = $db->prepare("DELETE FROM dns WHERE nome=?");
        $stmt->execute([(string)$_GET["delete"]]);
    }
    header("Location: dns.php?r=excluido");
    exit;
}

if ($isRev) {
    $st = $db->prepare("SELECT id, nome, url FROM revendedor_dns WHERE revendedor_id=? ORDER BY nome ASC");
    $st->execute([$revId]);
    $rowsDns = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
} else {
    $st = $db->query("SELECT nome, url FROM dns ORDER BY nome ASC");
    $rowsDns = $st ? ($st->fetchAll(PDO::FETCH_ASSOC) ?: []) : [];
}

$rowU = null;
if (isset($_GET["update"])) {
    if ($isRev) {
        $id = (int)$_GET["update"];
        $stmt = $db->prepare("SELECT id, nome, url FROM revendedor_dns WHERE id=? AND revendedor_id=? LIMIT 1");
        $stmt->execute([$id, $revId]);
        $rowU = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } else {
        $stmt = $db->prepare("SELECT nome, url FROM dns WHERE nome=? LIMIT 1");
        $stmt->execute([(string)$_GET["update"]]);
        $rowU = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
    if (!$rowU) {
        header("Location: dns.php");
        exit;
    }
}

if (isset($_GET['r'])) {
    $map = ['adicionado' => 'DNS salvo com sucesso.', 'atualizado' => 'DNS atualizado com sucesso.', 'excluido' => 'DNS apagado com sucesso.'];
    $msg = $map[(string)$_GET['r']] ?? '';
    $msgType = 'success';
}
?>

<?php require_once __DIR__ . '/../includes/header.php'; ?>
<div class="dns-wrap">
    <?php if ($msg !== ''): ?>
        <div class="alert alert-<?= htmlspecialchars($msgType, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <div class="card radius-10 dns-card">

<?php if (isset($_GET["create"])) { ?>

<div class="card-header bg-transparent dns-header">
    <div class="dns-title"><div class="ic"><i class="bi bi-plus-circle-fill"></i></div><div><h5>Adicionar DNS</h5><small><?= $isRev ? 'Cadastre um DNS exclusivo da sua revenda' : 'Cadastre um novo DNS global no sistema' ?></small></div></div>
    <div class="dns-actions"><span class="badge-soft"><i class="bi bi-globe-americas"></i> DNS</span><a href="dns.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Voltar</a></div>
</div>

<div class="card-body">
<form method="post">
    <div class="form-group mb-4"><label class="fw-900">Nome</label><input class="form-control" name="nome" required></div>
    <div class="form-group mb-4"><label class="fw-900">DNS</label><input class="form-control" name="url" required placeholder="http://servidor:porta"></div>
    <div class="d-flex gap-2 flex-wrap"><button class="btn btn-primary" name="submit"><i class="bi bi-check2-circle"></i> Salvar</button><a href="dns.php" class="btn btn-outline-secondary"><i class="bi bi-x-circle"></i> Cancelar</a></div>
</form>
</div>

<?php } elseif (isset($_GET["update"])) { ?>

<div class="card-header bg-transparent dns-header">
    <div class="dns-title"><div class="ic"><i class="bi bi-pencil-square"></i></div><div><h5>Editar DNS</h5><small>Atualize dados do DNS selecionado</small></div></div>
    <div class="dns-actions"><span class="badge-soft"><i class="bi bi-globe2"></i> Editar</span><a href="dns.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Voltar</a></div>
</div>

<div class="card-body">
<form method="post">
    <div class="form-group mb-4"><label class="fw-900">Nome</label><input class="form-control" name="nome" value="<?= htmlspecialchars((string)$rowU["nome"], ENT_QUOTES, 'UTF-8') ?>" required></div>
    <div class="form-group mb-4"><label class="fw-900">DNS</label><input class="form-control" name="url" value="<?= htmlspecialchars((string)$rowU["url"], ENT_QUOTES, 'UTF-8') ?>" required></div>
    <div class="d-flex gap-2 flex-wrap"><button class="btn btn-primary" name="submitU"><i class="bi bi-save2"></i> Salvar alterações</button><a href="dns.php" class="btn btn-outline-secondary"><i class="bi bi-x-circle"></i> Cancelar</a></div>
</form>
</div>

<?php } else { ?>

<div class="card-header bg-transparent dns-header">
    <div class="dns-title"><div class="ic"><i class="bi bi-globe"></i></div><div><h5><?= $isRev ? 'Meus DNS' : 'DNS Cadastrados' ?></h5><small><?= $isRev ? 'DNS próprios da revenda para cadastro de clientes' : 'Gerencie DNS globais do sistema' ?></small></div></div>
    <div class="dns-actions"><?php if (!$isRev): ?><a href="migrar_dns.php" class="btn btn-warning"><i class="bi bi-shuffle"></i> Trocar DNS All</a><?php endif; ?><a href="dns.php?create" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Adicionar DNS</a></div>
</div>

<div class="card-body p-0">
    <div class="table-responsive">
        <table class="table table-hover table-sm align-middle">
            <thead><tr><th>Nome</th><th>DNS</th><th class="text-end">Ações</th></tr></thead>
            <tbody>
            <?php if (!$rowsDns): ?>
                <tr><td colspan="3" class="text-center py-4">Nenhum DNS cadastrado.</td></tr>
            <?php endif; ?>
            <?php foreach ($rowsDns as $d): ?>
                <?php $updateKey = $isRev ? (string)$d['id'] : (string)$d['nome']; $deleteKey = $updateKey; ?>
                <tr>
                    <td><span class="pill"><i class="bi bi-tag"></i><?= htmlspecialchars((string)$d['nome'], ENT_QUOTES, 'UTF-8') ?></span></td>
                    <td><?= htmlspecialchars((string)$d['url'], ENT_QUOTES, 'UTF-8') ?></td>
                    <td><div class="row-actions"><a class="btn btn-sm btn-outline-primary" href="dns.php?update=<?= urlencode($updateKey) ?>"><i class="bi bi-pencil"></i> Editar</a><a class="btn btn-sm btn-outline-danger" data-confirm="Apagar este DNS?" href="dns.php?delete=<?= urlencode($deleteKey) ?>"><i class="bi bi-trash"></i> Apagar</a></div></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php } ?>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
