<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Configurações
define('DNS_DB', 'api/.db.db');
define('HISTORY_FILE', 'api/dns_migrations.json');
define('DATE_FORMAT', 'd/m/Y H:i:s');

// Inicialização do banco
try {
    $db = new SQLite3(DNS_DB);
    $db->busyTimeout(5000);
} catch (Exception $e) {
    die("Erro ao conectar ao banco de dados: " . $e->getMessage());
}

// Gerenciamento do histórico
if (!file_exists(HISTORY_FILE)) {
    file_put_contents(HISTORY_FILE, json_encode([], JSON_PRETTY_PRINT));
}

// Processar ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clear_history'])) {
        file_put_contents(HISTORY_FILE, json_encode([], JSON_PRETTY_PRINT));
        $_SESSION['alert'] = [
            'type' => 'success',
            'message' => 'Histórico limpo com sucesso!'
        ];
        header("Location: migrar.php");
        exit;
    }

    if (isset($_POST['new_dns'], $_POST['old_dns'])) {
        $new_dns = trim($db->escapeString($_POST['new_dns']));
        $old_dns = trim($db->escapeString($_POST['old_dns']));

        if (!empty($new_dns) && !empty($old_dns)) {
            $history = json_decode(file_get_contents(HISTORY_FILE), true) ?? [];
            array_unshift($history, [
                'old_dns' => $old_dns,
                'new_dns' => $new_dns,
                'migration_date' => date(DATE_FORMAT),
                'migrated_by' => 'admin'
            ]);
            file_put_contents(HISTORY_FILE, json_encode($history, JSON_PRETTY_PRINT));

            $stmt = $db->prepare("UPDATE dns SET url = :new WHERE url = :old");
            $stmt->bindValue(':new', $new_dns, SQLITE3_TEXT);
            $stmt->bindValue(':old', $old_dns, SQLITE3_TEXT);
            $stmt->execute();

            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => 'DNS migrado com sucesso!'
            ];
            header("Location: migrar.php");
            exit;
        }
    }
}

// Carregar dados
$dns_list = [];
$result = $db->query('SELECT DISTINCT url FROM dns ORDER BY url');
while ($row = $result->fetchArray()) {
    $dns_list[] = $row['url'];
}

$migration_history = json_decode(file_get_contents(HISTORY_FILE), true) ?? [];

include 'includes/header.php';
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Migração DNS | Painel Admin</title>
    <style>
    :root {
        --primary-blue: #1a237e;
        --dark-blue: #0d1541;
        --accent-blue: #3d5afe;
        --light-blue: #e8eaf6;
        --danger-red: #dc3545;
        --success-green: #28a745;
        --warning-orange: #fd7e14;
        --white: #ffffff;
        --light-gray: #f8f9fa;
        --medium-gray: #e9ecef;
        --dark-gray: #6c757d;
        --black: #212529;
    }
    
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: var(--light-gray);
        color: var(--black);
    }
    
    .container-fluid {
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
    }
    
    /* Cards - Estilo igual ao qrcode.php */
    .card {
        border: none;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        margin-bottom: 25px;
        background-color: var(--white);
        border: 1px solid var(--light-blue);
    }
    
    .card-header {
        border-radius: 10px 10px 0 0 !important;
        padding: 18px 25px;
        font-weight: 600;
        color: var(--white);
        background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%) !important;
    }
    
    .card-body {
        padding: 30px;
    }
    
    /* Seções - Estilo similar ao qrcode.php */
    .migration-section {
        margin-bottom: 35px;
        padding-bottom: 35px;
        border-bottom: 1px solid var(--medium-gray);
    }
    
    .migration-section:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }
    
    .section-title {
        color: var(--primary-blue);
        margin-bottom: 25px;
        font-size: 1.2rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .section-title i {
        margin-right: 12px;
        font-size: 1.3rem;
        color: var(--accent-blue);
    }
    
    /* Formulário - Ajustado para campos lado a lado */
    .form-row {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .form-group {
        flex: 1;
        min-width: 250px;
        max-width: 400px;
    }
    
    .form-control {
        padding: 12px 15px;
        border-radius: 8px;
        border: 1px solid var(--medium-gray);
        transition: all 0.3s;
        width: 100%;
        text-align: center;
    }
    
    .form-control:focus {
        border-color: var(--accent-blue);
        box-shadow: 0 0 0 3px rgba(61, 90, 254, 0.15);
    }
    
    .form-label {
        font-weight: 500;
        margin-bottom: 10px;
        color: var(--dark-blue);
        text-align: center;
        display: block;
    }
    
    /* Botões - Centralizados */
    .btn-container {
        display: flex;
        justify-content: center;
        margin-top: 30px;
    }
    
    .btn {
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
    
    .btn-primary {
        background-color: var(--primary-blue);
        border-color: var(--primary-blue);
        color: var(--white);
    }
    
    .btn-primary:hover {
        background-color: var(--dark-blue);
        transform: translateY(-2px);
    }
    
    .btn-danger {
        background-color: var(--danger-red);
        border-color: var(--danger-red);
        color: var(--white);
    }
    
    .btn-danger:hover {
        background-color: #c82333;
    }
    
    /* Tabela */
    .table-container {
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid var(--light-blue);
        margin: 0 auto;
        max-width: 1000px;
    }
    
    .table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .table th {
        background-color: var(--light-blue);
        color: var(--dark-blue);
        padding: 12px 15px;
        text-align: center;
    }
    
    .table td {
        padding: 12px 15px;
        border-bottom: 1px solid var(--medium-gray);
        text-align: center;
    }
    
    .table tr:last-child td {
        border-bottom: none;
    }
    
    .table tr:hover td {
        background-color: var(--light-blue);
    }
    
    /* Badges */
    .badge {
        padding: 5px 10px;
        border-radius: 50px;
        font-size: 0.85rem;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
    }
    
    .badge-info {
        background-color: var(--accent-blue);
        color: white;
    }
    
    .badge-success {
        background-color: var(--success-green);
        color: white;
    }
    
    /* Alertas */
    .alert {
        border-radius: 8px;
        padding: 15px 20px;
        margin: 25px auto;
        display: flex;
        align-items: center;
        justify-content: center;
        max-width: 800px;
    }
    
    .alert-success {
        background-color: rgba(40, 167, 69, 0.1);
        border-left: 4px solid var(--success-green);
        color: var(--success-green);
    }
    
    .alert-danger {
        background-color: rgba(220, 53, 69, 0.1);
        border-left: 4px solid var(--danger-red);
        color: var(--danger-red);
    }
    
    /* Estado vazio */
    .empty-state {
        text-align: center;
        padding: 40px 20px;
    }
    
    .empty-state i {
        font-size: 3rem;
        color: var(--light-blue);
        margin-bottom: 15px;
    }
    
    /* URL */
    .url {
        font-family: 'Courier New', monospace;
        font-size: 0.9rem;
        word-break: break-all;
    }
    
    /* Responsivo */
    @media (max-width: 768px) {
        .card-body {
            padding: 20px;
        }
        
        .form-row {
            flex-direction: column;
            align-items: center;
            gap: 15px;
        }
        
        .form-group {
            width: 100%;
            max-width: 100%;
        }
        
        .table th, 
        .table td {
            padding: 8px 10px;
            font-size: 0.85rem;
        }
        
        .btn {
            width: 100%;
            max-width: 300px;
        }
        
        .table-responsive {
            overflow-x: auto;
            display: block;
            width: 100%;
        }
    }
    
    @media (max-width: 576px) {
        .section-title {
            flex-direction: column;
            text-align: center;
        }
        
        .section-title i {
            margin-right: 0;
            margin-bottom: 8px;
        }
        
        .card-header {
            text-align: center;
        }
        
        .btn-container {
            flex-direction: column;
            align-items: center;
            gap: 10px;
        }
    }
    </style>
</head>
<body>
    <div class="container-fluid py-4">
        <!-- Alertas -->
        <?php if (isset($_SESSION['alert'])): ?>
            <div class="alert alert-<?= $_SESSION['alert']['type'] ?>">
                <i class="fas <?= $_SESSION['alert']['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?> me-2"></i>
                <?= $_SESSION['alert']['message'] ?>
                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['alert']); ?>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-8 mx-auto">
                <!-- Card de Migração -->
                <div class="card shadow-sm">
                    <div class="card-header">
                        <div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
                            <h4 class="mb-2 mb-md-0"><i class="fas fa-exchange-alt me-2"></i>Migração DNS</h4>
                            <a href="dns.php" class="btn btn-light">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Seção de Migração -->
                        <div class="migration-section">
                            <h5 class="section-title">
                                <i class="fas fa-sync-alt"></i>Migrar Endereço DNS
                            </h5>
                            
                            <form method="POST" class="needs-validation" novalidate>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="old_dns" class="form-label">DNS Atual</label>
                                        <select class="form-control" id="old_dns" name="old_dns" required>
                                            <option value="" selected disabled>Selecione um DNS...</option>
                                            <?php foreach ($dns_list as $dns): ?>
                                                <option value="<?= htmlspecialchars($dns) ?>"><?= htmlspecialchars($dns) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="invalid-feedback">
                                            Por favor, selecione um DNS para migrar.
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="new_dns" class="form-label">Novo DNS</label>
                                        <input type="url" class="form-control" id="new_dns" name="new_dns" 
                                               placeholder="https://novo.dominio.com" required>
                                        <div class="invalid-feedback">
                                            Por favor, informe um endereço DNS válido.
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="btn-container">
                                    <button type="submit" class="btn btn-primary px-5">
                                        <i class="fas fa-paper-plane me-2"></i>Migrar DNS
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Seção de Histórico -->
                        <div class="migration-section">
                            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mb-3">
                                <h5 class="section-title mb-3 mb-md-0">
                                    <i class="fas fa-history"></i>Histórico de Migrações
                                </h5>
                                <?php if (!empty($migration_history)): ?>
                                    <form method="POST">
                                        <button type="submit" name="clear_history" class="btn btn-danger">
                                            <i class="fas fa-trash-alt me-1"></i> Limpar Histórico
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (!empty($migration_history)): ?>
                                <div class="table-responsive">
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>DNS Anterior</th>
                                                <th>DNS Novo</th>
                                                <th>Data/Hora</th>
                                                <th>Responsável</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($migration_history as $record): ?>
                                                <tr>
                                                    <td><div class="url"><?= htmlspecialchars($record['old_dns']) ?></div></td>
                                                    <td><div class="url"><?= htmlspecialchars($record['new_dns']) ?></div></td>
                                                    <td>
                                                        <span class="badge badge-info">
                                                            <i class="far fa-clock me-1"></i>
                                                            <?= htmlspecialchars($record['migration_date']) ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-success">
                                                            <i class="fas fa-user-shield me-1"></i>
                                                            admin
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <h5>Nenhuma migração registrada</h5>
                                    <p>O histórico de migrações aparecerá aqui</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Validação de formulário
    (function () {
        'use strict'
        
        var forms = document.querySelectorAll('.needs-validation')
        
        Array.prototype.slice.call(forms)
            .forEach(function (form) {
                form.addEventListener('submit', function (event) {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    }
                    
                    form.classList.add('was-validated')
                }, false)
            })
    })()
    
    // Fechar alertas automaticamente
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
    </script>
</body>
</html>

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