<?php
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

$id_store = $_SESSION['id'];

if ($_SESSION['store_type'] == 2) {
    header("Location: users_mac.php");
    exit();
}

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

if (isset($_POST["update_domain"])) {
    $dominio_antigo = trim($_POST['old_domain']);
    $dominio_novo = trim($_POST['new_domain']);
    $id_user = $_SESSION['id']; 

    $stmt_check = $db->prepare("SELECT COUNT(*) as count FROM ibo WHERE dns LIKE :old AND id_user = :user");
    $stmt_check->bindValue(':old', '%'.$dominio_antigo.'%', SQLITE3_TEXT);
    $stmt_check->bindValue(':user', $id_user, SQLITE3_TEXT);
    $row = $stmt_check->execute()->fetchArray();

    if ($row['count'] > 0) {
        $stmt_up = $db->prepare("UPDATE ibo SET 
            dns = REPLACE(dns, :old, :new), 
            url = REPLACE(url, :old, :new) 
            WHERE id_user = :user");
        $stmt_up->bindValue(':old', $dominio_antigo, SQLITE3_TEXT);
        $stmt_up->bindValue(':new', $dominio_novo, SQLITE3_TEXT);
        $stmt_up->bindValue(':user', $id_user, SQLITE3_TEXT);
        
        if($stmt_up->execute()) {
            $_SESSION['msg_type'] = "success";
            $_SESSION['msg_text'] = "DOMÍNIO ATUALIZADO EM " . $row['count'] . " CLIENTES!";
        }
    } else {
        $_SESSION['msg_type'] = "error";
        $_SESSION['msg_text'] = "O DOMÍNIO ANTIGO NÃO FOI ENCONTRADO.";
    }
    header("Location: replace.php");
    exit();
}

include "includes/header.php";
?>

<style>
    /* RESET E SEGURANÇA */
    * { box-sizing: border-box; }

    /* FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }

    /* OCULTAR ELEMENTOS DO HEADER */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR */
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
        max-width: 650px;
        margin-left: auto;
        margin-right: auto;
    }

    /* CARD PREMIUM CENTRALIZADO */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        max-width: 650px;
        margin: 0 auto 40px auto;
        width: 100%;
        animation: fadeIn 0.4s ease-in-out;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: scale(0.98); }
        to { opacity: 1; transform: scale(1); }
    }

    .card-header-premium { 
        margin-bottom: 25px; 
        border-bottom: 1px solid rgba(255,255,255,0.05); 
        padding-bottom: 15px; 
    }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #f59e0b; font-size: 0.8rem; margin-top: 4px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }

    /* INFO BOX DE ALERTA */
    .info-box-premium {
        background: rgba(245, 158, 11, 0.08);
        border: 1px solid rgba(245, 158, 11, 0.2);
        padding: 18px;
        border-radius: 15px;
        margin-bottom: 30px;
        display: flex;
        gap: 15px;
        align-items: flex-start;
    }
    .info-box-premium i { color: #f59e0b; font-size: 1.4rem; margin-top: 2px; }
    .info-box-premium div span { display: block; color: #f59e0b; font-weight: 800; font-size: 0.75rem; text-transform: uppercase; margin-bottom: 4px; }
    .info-box-premium div p { color: #94a3b8; font-size: 0.85rem; line-height: 1.5; margin: 0; }

    /* FORMULÁRIO */
    label { 
        display: block; color: #64748b; font-size: 0.7rem; font-weight: 800; 
        margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;
    }

    .form-input { 
        width: 100%; 
        background: #0f172a !important; 
        border: 1px solid #1e293b !important; 
        color: #fff !important; 
        padding: 16px; 
        border-radius: 12px; 
        font-size: 0.95rem; 
        margin-bottom: 25px; 
        transition: 0.3s;
    }
    .form-input:focus { border-color: #f59e0b !important; outline: none; box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1); }
    .form-input::placeholder { color: #334155; }

    /* BOTÕES */
    .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 10px; }
    
    .btn-premium-replace {
        background: #f59e0b !important; color: #000 !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px;
        box-shadow: 0 4px 15px rgba(245, 158, 11, 0.2);
        transition: 0.3s;
    }
    .btn-premium-replace:hover { filter: brightness(1.1); transform: translateY(-2px); }
    .btn-premium-replace:active { transform: translateY(0); }
    
    .btn-premium-cancel {
        background: #1e293b !important; color: #94a3b8 !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        text-align: center; text-decoration: none !important;
        transition: 0.3s;
    }
    .btn-premium-cancel:hover { background: #334155 !important; color: #fff !important; }

    @media (min-width: 768px) {
        .row-buttons { grid-template-columns: 2fr 1fr; }
    }
</style>

<div class="container-fluid">
    <div style="max-width: 650px; margin: 0 auto;">
        <a href="index.php" class="btn-back-nav">
            <i class="fas fa-chevron-left"></i> Voltar ao Dashboard
        </a>
    </div>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Substituir DNS</h1>
            <p><i class="fas fa-tools mr-1"></i> Manutenção de Infraestrutura</p>
        </div>

        <div class="info-box-premium">
            <i class="fas fa-exclamation-triangle"></i>
            <div>
                <span>Atenção Crítica</span>
                <p>Esta ferramenta altera o DNS de <b>todos</b> os clientes do seu painel de uma única vez. Use apenas se o servidor antigo estiver offline.</p>
            </div>
        </div>

        <form method="post" id="formReplace">
            <label>DNS Atual (O que será substituído)</label>
            <input type="text" class="form-input" name="old_domain" placeholder="http://antigo.com:8080" required>

            <label>Novo DNS (O que entrará no lugar)</label>
            <input type="text" class="form-input" name="new_domain" placeholder="http://novo-servidor.xyz:80" required>

            <input type="hidden" name="update_domain" value="1">

            <div class="row-buttons">
                <button type="button" id="btnConfirmReplace" class="btn-premium-replace">
                    <i class="fas fa-sync-alt"></i> Executar Substituição
                </button>
                <a href="index.php" class="btn-premium-cancel">Cancelar</a>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        // Alerta de Confirmação antes de rodar o SQL
        $('#btnConfirmReplace').on('click', function() {
            const oldD = $('input[name="old_domain"]').val();
            const newD = $('input[name="new_domain"]').val();

            if(!oldD || !newD) {
                Swal.fire({ 
                    icon: 'error', 
                    title: 'Campos Vazios', 
                    text: 'Você precisa informar o DNS antigo e o novo.', 
                    background: '#070e1b', 
                    color: '#fff',
                    confirmButtonColor: '#f59e0b'
                });
                return;
            }

            Swal.fire({
                title: 'Confirmar Migração?',
                html: `Você está prestes a remover o DNS <br><b style="color:#ef4444">${oldD}</b><br> e aplicar o novo <br><b style="color:#2ecc71">${newD}</b> em todos os clientes.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f59e0b',
                cancelButtonColor: '#1e293b',
                confirmButtonText: 'Sim, Migrar Agora!',
                cancelButtonText: 'Cancelar',
                background: '#070e1b',
                color: '#fff'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Processando...',
                        text: 'Aguarde enquanto o banco de dados é atualizado.',
                        allowOutsideClick: false,
                        didOpen: () => { Swal.showLoading(); }
                    });
                    $('#formReplace').submit();
                }
            });
        });

        // Alertas de Resultado vindos da Sessão
        <?php if (isset($_SESSION['msg_type'])): ?>
            Swal.fire({
                icon: '<?= $_SESSION['msg_type'] ?>',
                title: '<?= ($_SESSION['msg_type'] == "success") ? "Sucesso!" : "Ocorreu um Erro" ?>',
                text: '<?= $_SESSION['msg_text'] ?>',
                background: '#070e1b',
                color: '#fff',
                confirmButtonColor: '<?= ($_SESSION['msg_type'] == "success") ? "#2ecc71" : "#ef4444" ?>'
            });
            <?php unset($_SESSION['msg_type'], $_SESSION['msg_text']); ?>
        <?php endif; ?>
    });
</script>

<?php 
$db->close();
include "includes/footer.php"; 
?>
