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

$db = new SQLite3(dirname(__DIR__) . "/api/db.db");

$base_file = basename($_SERVER["SCRIPT_NAME"]);

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

    if ($nome && $url) {
        $stmt = $db->prepare("INSERT OR REPLACE INTO dns (nome, url) VALUES (:n, :u)");
        $stmt->bindValue(":n", $nome, SQLITE3_TEXT);
        $stmt->bindValue(":u", $url, SQLITE3_TEXT);
        $stmt->execute();
        header("Location: dns.php?r=adicionado");
        exit;
    }
}

if (isset($_POST["submitU"])) {
    $nome = trim($_POST["nome"]);
    $url = trim($_POST["url"]);
    $old = $_GET["update"];

    $stmt = $db->prepare("UPDATE dns SET nome=:n, url=:u WHERE nome=:o");
    $stmt->bindValue(":n", $nome, SQLITE3_TEXT);
    $stmt->bindValue(":u", $url, SQLITE3_TEXT);
    $stmt->bindValue(":o", $old, SQLITE3_TEXT);
    $stmt->execute();
    header("Location: dns.php?r=atualizado");
    exit;
}

if (isset($_GET["delete"])) {
    $stmt = $db->prepare("DELETE FROM dns WHERE nome=:n");
    $stmt->bindValue(":n", $_GET["delete"], SQLITE3_TEXT);
    $stmt->execute();
    header("Location: dns.php?r=excluido");
    exit;
}

$res = $db->query("SELECT * FROM dns ORDER BY nome ASC");

$rowU = null;
if (isset($_GET["update"])) {
    $stmt = $db->prepare("SELECT * FROM dns WHERE nome=:n");
    $stmt->bindValue(":n", $_GET["update"], SQLITE3_TEXT);
    $r = $stmt->execute();
    $rowU = $r->fetchArray(SQLITE3_ASSOC);
}
?>

<?php include './includes/header.php'; ?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
/* =====================================================
   DNS PAGE — RESPONSIVO MOBILE FIRST
====================================================== */
.dns-wrap {
    max-width: 1100px;
    margin: 0 auto;
    padding: 0 4px;
}

/* Card principal */
.dns-card {
    border-radius: 18px;
    overflow: hidden;
    border: 1px solid rgba(34,197,94,.2) !important;
    background: #ffffff !important;
}

/* Header do card */
.dns-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 16px 18px;
    background: #ffffff !important;
    border-bottom: 1px solid #e5e7eb !important;
    flex-wrap: wrap;
}
.dns-title {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}
.dns-title .ic {
    width: 44px;
    height: 44px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(34,197,94,.12);
    flex-shrink: 0;
}
.dns-title .ic i {
    font-size: 22px;
    color: #16a34a;
}
.dns-title h5 {
    margin: 0;
    font-weight: 700;
    font-size: 16px;
    color: #111827 !important;
}
.dns-title small {
    color: #6b7280;
    font-size: 12px;
}
.dns-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
}

/* Botões */
.dns-btn {
    border-radius: 12px;
    height: 40px;
    padding: 0 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    font-weight: 700;
    font-size: 13px;
    border: none;
    cursor: pointer;
    text-decoration: none;
    white-space: nowrap;
    transition: opacity .18s, transform .12s;
}
.dns-btn:active { transform: scale(.97); }
.dns-btn-primary {
    background: #16a34a;
    color: #fff !important;
}
.dns-btn-primary:hover { background: #15803d; color: #fff !important; }
.dns-btn-warning {
    background: #ca8a04;
    color: #fff !important;
}
.dns-btn-warning:hover { background: #a16207; color: #fff !important; }
.dns-btn-secondary {
    background: #f3f4f6;
    color: #374151 !important;
    border: 1px solid #e5e7eb;
}
.dns-btn-secondary:hover { background: #e5e7eb; color: #111827 !important; }
.dns-btn-danger {
    background: rgba(239,68,68,.1);
    color: #dc2626 !important;
    border: 1px solid rgba(239,68,68,.25);
}
.dns-btn-danger:hover { background: rgba(239,68,68,.2); }
.dns-btn-edit {
    background: rgba(34,197,94,.1);
    color: #16a34a !important;
    border: 1px solid rgba(34,197,94,.25);
}
.dns-btn-edit:hover { background: rgba(34,197,94,.2); }

/* Badge */
.dns-badge {
    background: rgba(34,197,94,.1);
    color: #16a34a;
    border: 1px solid rgba(34,197,94,.25);
    border-radius: 999px;
    padding: 6px 12px;
    font-size: 12px;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    white-space: nowrap;
}

/* Formulário */
.dns-card-body {
    padding: 20px 18px;
    background: #ffffff !important;
}
.dns-label {
    font-weight: 700;
    font-size: 13px;
    color: #374151;
    display: block;
    margin-bottom: 6px;
}
.dns-input {
    width: 100%;
    background: #f9fafb !important;
    border: 1px solid #e5e7eb !important;
    border-radius: 12px !important;
    height: 46px;
    padding: 0 14px;
    color: #111827 !important;
    font-size: 14px;
    outline: none;
    transition: border-color .2s;
}
.dns-input:focus {
    border-color: rgba(34,197,94,.5) !important;
    box-shadow: 0 0 0 3px rgba(34,197,94,.08);
}
.dns-input::placeholder { color: #9ca3af; opacity: 1; }
.dns-form-group { margin-bottom: 18px; }
.dns-form-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    padding-top: 4px;
}

/* Tabela desktop */
.dns-table-wrap {
    width: 100%;
    background: #ffffff;
}
.dns-table {
    width: 100%;
    border-collapse: collapse;
}
.dns-table thead th {
    font-size: 11px;
    letter-spacing: .5px;
    text-transform: uppercase;
    color: #6b7280;
    padding: 12px 18px;
    border-bottom: 1px solid #e5e7eb;
    font-weight: 700;
    background: #f9fafb;
}
.dns-table tbody tr {
    border-bottom: 1px solid #f3f4f6;
    transition: background .15s;
}
.dns-table tbody tr:last-child { border-bottom: none; }
.dns-table tbody tr:hover { background: #f9fafb; }
.dns-table td {
    padding: 14px 18px;
    vertical-align: middle;
}
.dns-row-name {
    font-weight: 700;
    font-size: 14px;
    color: #111827;
}
.dns-row-sub {
    font-size: 12px;
    color: #6b7280;
    margin-top: 3px;
}
.dns-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 11px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 600;
    background: rgba(34,197,94,.08);
    border: 1px solid rgba(34,197,94,.2);
    color: #16a34a;
    word-break: break-all;
}
.dns-row-actions {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
    flex-wrap: wrap;
}

/* =====================================================
   MOBILE: cards em vez de tabela
====================================================== */
@media (max-width: 640px) {

    .dns-wrap { padding: 0; }

    .dns-header {
        padding: 14px;
        gap: 10px;
    }
    .dns-title .ic {
        width: 38px;
        height: 38px;
    }
    .dns-title .ic i { font-size: 18px; }
    .dns-title h5 { font-size: 14px; }
    .dns-actions { width: 100%; }
    .dns-badge { display: none; }
    .dns-btn { height: 38px; font-size: 12.5px; padding: 0 12px; flex: 1; }

    /* Esconde tabela no mobile */
    .dns-table-desktop { display: none !important; }

    /* Cards mobile */
    .dns-mobile-list {
        display: flex !important;
        flex-direction: column;
        gap: 0;
    }
    .dns-mobile-card {
        padding: 14px 16px;
        border-bottom: 1px solid #f3f4f6;
        background: #ffffff;
    }
    .dns-mobile-card:last-child { border-bottom: none; }
    .dns-mobile-top {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 10px;
    }
    .dns-mobile-info { flex: 1; min-width: 0; }
    .dns-mobile-name {
        font-weight: 700;
        font-size: 14px;
        color: #111827;
    }
    .dns-mobile-url {
        font-size: 12px;
        color: #6b7280;
        word-break: break-all;
        margin-top: 4px;
        display: flex;
        align-items: flex-start;
        gap: 5px;
    }
    .dns-mobile-url i { margin-top: 2px; flex-shrink: 0; }
    .dns-mobile-actions {
        display: flex;
        gap: 8px;
    }
    .dns-btn-icon {
        width: 36px;
        height: 36px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        flex-shrink: 0;
        text-decoration: none;
        transition: background .15s;
    }
    .dns-btn-icon-edit {
        background: rgba(34,197,94,.1);
        color: #16a34a !important;
        border: 1px solid rgba(34,197,94,.2);
    }
    .dns-btn-icon-del {
        background: rgba(239,68,68,.1);
        color: #dc2626 !important;
        border: 1px solid rgba(239,68,68,.2);
    }

    /* Form mobile */
    .dns-card-body { padding: 16px; }
    .dns-form-actions .dns-btn { flex: 1; min-width: calc(50% - 5px); }
}

@media (min-width: 641px) {
    .dns-table-desktop { display: block !important; }
    .dns-mobile-list   { display: none !important; }
}
</style>

<div class="dns-wrap">
    <div class="card dns-card">

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

<div class="dns-header">
    <div class="dns-title">
        <div class="ic"><i class="bi bi-plus-circle-fill"></i></div>
        <div>
            <h5>Adicionar DNS</h5>
            <small>Cadastre um novo DNS no sistema</small>
        </div>
    </div>
    <div class="dns-actions">
        <span class="dns-badge"><i class="bi bi-globe-americas"></i> DNS</span>
        <a href="dns.php" class="dns-btn dns-btn-secondary"><i class="bi bi-arrow-left"></i> Voltar</a>
    </div>
</div>

<div class="dns-card-body">
    <form method="post">
        <div class="dns-form-group">
            <label class="dns-label">Nome</label>
            <input class="dns-input" name="nome" required placeholder="Ex: Servidor BR 01">
        </div>
        <div class="dns-form-group">
            <label class="dns-label">DNS</label>
            <input class="dns-input" name="url" required placeholder="Ex: dns.exemplo.com.br">
        </div>
        <div class="dns-form-actions">
            <button class="dns-btn dns-btn-primary" name="submit"><i class="bi bi-check2-circle"></i> Salvar</button>
            <a href="migrar_dns.php" class="dns-btn dns-btn-warning"><i class="bi bi-shuffle"></i> Trocar All</a>
            <a href="dns.php" class="dns-btn dns-btn-secondary"><i class="bi bi-x-circle"></i> Cancelar</a>
        </div>
    </form>
</div>

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

<div class="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="dns-badge"><i class="bi bi-globe2"></i> Editar</span>
        <a href="dns.php" class="dns-btn dns-btn-secondary"><i class="bi bi-arrow-left"></i> Voltar</a>
    </div>
</div>

<div class="dns-card-body">
    <form method="post">
        <div class="dns-form-group">
            <label class="dns-label">Nome</label>
            <input class="dns-input" name="nome" value="<?= htmlspecialchars($rowU["nome"]) ?>" required>
        </div>
        <div class="dns-form-group">
            <label class="dns-label">DNS</label>
            <input class="dns-input" name="url" value="<?= htmlspecialchars($rowU["url"]) ?>" required>
        </div>
        <div class="dns-form-actions">
            <button class="dns-btn dns-btn-primary" name="submitU"><i class="bi bi-save2"></i> Salvar</button>
            <a href="migrar_dns.php" class="dns-btn dns-btn-warning"><i class="bi bi-shuffle"></i> Trocar All</a>
            <a href="dns.php" class="dns-btn dns-btn-secondary"><i class="bi bi-x-circle"></i> Cancelar</a>
        </div>
    </form>
</div>

<?php } else { ?>

<div class="dns-header">
    <div class="dns-title">
        <div class="ic"><i class="bi bi-globe"></i></div>
        <div>
            <h5>DNS Cadastrados</h5>
            <small>Gerencie e troque DNS em massa</small>
        </div>
    </div>
    <div class="dns-actions">
        <span class="dns-badge"><i class="bi bi-shield-check"></i> Premium</span>
        <a href="migrar_dns.php" class="dns-btn dns-btn-warning"><i class="bi bi-shuffle"></i> Trocar All</a>
        <a href="dns.php?create" class="dns-btn dns-btn-primary"><i class="bi bi-plus-lg"></i> Adicionar</a>
    </div>
</div>

<?php
// Coleta os resultados para usar nas duas versões (desktop e mobile)
$dns_rows = [];
while ($r = $res->fetchArray(SQLITE3_ASSOC)) {
    $dns_rows[] = $r;
}
?>

<!-- TABELA DESKTOP -->
<div class="dns-table-desktop">
    <div class="dns-table-wrap">
        <table class="dns-table">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>DNS</th>
                    <th style="text-align:right;">Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($dns_rows as $r): ?>
                <tr>
                    <td>
                        <div class="dns-row-name"><?= htmlspecialchars($r["nome"]) ?></div>
                        <div class="dns-row-sub"><i class="bi bi-link-45deg"></i> Registro DNS</div>
                    </td>
                    <td>
                        <span class="dns-pill"><i class="bi bi-globe2"></i> <?= htmlspecialchars($r["url"]) ?></span>
                    </td>
                    <td>
                        <div class="dns-row-actions">
                            <a href="dns.php?update=<?= urlencode($r["nome"]) ?>" class="dns-btn dns-btn-edit">
                                <i class="bi bi-pencil-square"></i> Editar
                            </a>
                            <a href="dns.php?delete=<?= urlencode($r["nome"]) ?>" class="dns-btn dns-btn-danger">
                                <i class="bi bi-trash3-fill"></i> Excluir
                            </a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- CARDS MOBILE -->
<div class="dns-mobile-list">
    <?php foreach ($dns_rows as $r): ?>
    <div class="dns-mobile-card">
        <div class="dns-mobile-top">
            <div class="dns-mobile-info">
                <div class="dns-mobile-name"><?= htmlspecialchars($r["nome"]) ?></div>
                <div class="dns-mobile-url">
                    <i class="bi bi-globe2"></i>
                    <?= htmlspecialchars($r["url"]) ?>
                </div>
            </div>
            <div class="dns-mobile-actions">
                <a href="dns.php?update=<?= urlencode($r["nome"]) ?>" class="dns-btn-icon dns-btn-icon-edit" title="Editar">
                    <i class="bi bi-pencil-square"></i>
                </a>
                <a href="dns.php?delete=<?= urlencode($r["nome"]) ?>" class="dns-btn-icon dns-btn-icon-del" title="Excluir">
                    <i class="bi bi-trash3-fill"></i>
                </a>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php } ?>

    </div><!-- .dns-card -->
</div><!-- .dns-wrap -->

<?php
if (isset($_GET["r"])) {
    if ($_GET["r"] == "adicionado") echo "<script>Swal.fire({title:'DNS adicionado',icon:'success',background:'#0d1f17',color:'#e6faf0',confirmButtonColor:'#16a34a'})</script>";
    if ($_GET["r"] == "atualizado") echo "<script>Swal.fire({title:'DNS atualizado',icon:'success',background:'#0d1f17',color:'#e6faf0',confirmButtonColor:'#16a34a'})</script>";
    if ($_GET["r"] == "excluido")  echo "<script>Swal.fire({title:'DNS excluído',icon:'success',background:'#0d1f17',color:'#e6faf0',confirmButtonColor:'#16a34a'})</script>";
}
?>

<?php include './includes/footer.php'; ?>