<?php
session_start();

/**
 * ⚙️ Sistema DNSMAX - Migração de DNS (Versão Reforçada)
 * Foco: Blindagem contra SQL Injection, CSRF e Persistência Segura.
 */

// ==============================
// 🆕 CLASSE DE CONFIGURAÇÃO
// ==============================
final class Config
{
    const DNS_DB = __DIR__ . '/api/.db.db';
    const HISTORY_FILE = __DIR__ . '/api/dns_migrations.json';
    const DATE_FORMAT = 'd/m/Y H:i:s';
    const MAX_HISTORY = 50;
}

// Configurações de segurança para produção
ini_set('display_errors', '0');
error_reporting(E_ALL);

// Gera Token CSRF para proteção de formulários
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// ==============================
// 🆕 DBManager (PDO SQLite)
// ==============================
class DBManager
{
    private $pdo;

    public function __construct(string $filePath)
    {
        $dir = dirname($filePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        try {
            $this->pdo = new PDO("sqlite:" . $filePath);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            
            // Reforço: WAL Mode melhora performance em concorrência no SQLite
            $this->pdo->exec("PRAGMA journal_mode=WAL;");
            $this->pdo->exec("CREATE TABLE IF NOT EXISTS dns (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, url TEXT)");
        } catch (PDOException $e) {
            error_log("DB Error: " . $e->getMessage());
            throw new Exception("Falha na integridade do banco de dados.");
        }
    }

    public function fetchDistinctUrls(): array
    {
        $stmt = $this->pdo->query('SELECT DISTINCT url FROM dns WHERE url IS NOT NULL AND url != "" ORDER BY url');
        return $stmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    }

    public function updateUrl(string $oldUrl, string $newUrl): int
    {
        $this->pdo->beginTransaction();
        try {
            $stmt = $this->pdo->prepare('UPDATE dns SET url = :new WHERE url = :old');
            $stmt->execute([':new' => $newUrl, ':old' => $oldUrl]);
            $count = $stmt->rowCount();
            $this->pdo->commit();
            return $count;
        } catch (Exception $e) {
            $this->pdo->rollBack();
            throw $e;
        }
    }
}

// ==============================
// 🆕 HistoryManager (JSON Storage)
// ==============================
class HistoryManager
{
    private $file;

    public function __construct(string $filePath)
    {
        $this->file = $filePath;
    }

    public function getAll(): array
    {
        if (!file_exists($this->file)) return [];
        $content = file_get_contents($this->file);
        $data = json_decode($content, true);
        return is_array($data) ? $data : [];
    }

    public function record(string $old, string $new): void
    {
        $history = $this->getAll();
        array_unshift($history, [
            'old_dns' => $old,
            'new_dns' => $new,
            'migration_date' => date(Config::DATE_FORMAT),
            'migrated_by' => $_SESSION['user_name'] ?? 'admin',
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0' // Log de IP para auditoria
        ]);
        
        $data = json_encode(array_slice($history, 0, Config::MAX_HISTORY), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        file_put_contents($this->file, $data, LOCK_EX); // LOCK_EX evita corrupção de arquivo
    }

    public function clear(): void
    {
        if (file_exists($this->file)) {
            file_put_contents($this->file, json_encode([]), LOCK_EX);
        }
    }
}

// ==============================
// LÓGICA DE EXECUÇÃO
// ==============================
try {
    $db = new DBManager(Config::DNS_DB);
    $history = new HistoryManager(Config::HISTORY_FILE);
} catch (Exception $e) {
    die("Erro de Segurança: " . htmlspecialchars($e->getMessage()));
}

// Processar formulários POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validação CSRF
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Requisição inválida (CSRF).");
    }

    if (isset($_POST['clear_history'])) {
        $history->clear();
        $_SESSION['msg'] = ['success', 'Histórico limpo com sucesso!'];
    } elseif (!empty($_POST['old_dns']) && !empty($_POST['new_dns'])) {
        // Validação Estrita de URL
        $old = filter_var($_POST['old_dns'], FILTER_SANITIZE_URL);
        $new = filter_var($_POST['new_dns'], FILTER_SANITIZE_URL);
        
        if (!filter_var($new, FILTER_VALIDATE_URL)) {
            $_SESSION['msg'] = ['danger', "O formato da nova URL é inválido."];
        } else {
            try {
                $affected = $db->updateUrl($old, $new);
                if ($affected > 0) {
                    $history->record($old, $new);
                    $_SESSION['msg'] = ['success', "Sucesso! $affected registros migrados para: $new"];
                } else {
                    $_SESSION['msg'] = ['warning', "Nenhum registro encontrado para o DNS de origem."];
                }
            } catch (Exception $e) {
                $_SESSION['msg'] = ['danger', "Falha técnica na migração."];
            }
        }
    }
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$dnsList = $db->fetchDistinctUrls();
$logs = $history->getAll();
$msg = $_SESSION['msg'] ?? null;
unset($_SESSION['msg']);

if(file_exists('includes/header.php')) include 'includes/header.php';
?>

<div class="container py-5">
    <?php if ($msg): ?>
        <div class="alert alert-<?= $msg[0] ?> alert-dismissible fade show shadow-sm border-0" role="alert">
            <i class="fas fa-info-circle me-2"></i> <?= htmlspecialchars($msg[1]) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow border-0" style="border-radius: 15px;">
        <div class="card-header bg-primary text-white p-3" style="border-radius: 15px 15px 0 0;">
            <h5 class="mb-0"><i class="fas fa-shield-alt me-2"></i>Migração Segura de DNS</h5>
        </div>
        <div class="card-body p-4">
            <form method="POST" onsubmit="return confirm('ATENÇÃO: Deseja alterar todos os registros agora?');">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">DNS Atual (Origem)</label>
                        <select name="old_dns" class="form-select select2" required>
                            <option value="">Selecione o DNS...</option>
                            <?php foreach($dnsList as $d): ?>
                                <option value="<?= htmlspecialchars($d) ?>"><?= htmlspecialchars($d) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Novo DNS (Destino)</label>
                        <input type="url" name="new_dns" class="form-control" placeholder="https://novo-servidor.com" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary w-100 mt-2 py-2 fw-bold shadow-sm">
                    <i class="fas fa-sync-alt me-1"></i> Executar Migração
                </button>
            </form>

            <hr class="my-5">

            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="fw-bold mb-0 text-secondary"><i class="fas fa-history me-2"></i>Histórico de Auditoria</h6>
                <?php if($logs): ?>
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <button name="clear_history" class="btn btn-outline-danger btn-sm rounded-pill">
                        <i class="fas fa-trash-alt me-1"></i> Limpar Logs
                    </button>
                </form>
                <?php endif; ?>
            </div>

            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Origem</th>
                            <th>Destino</th>
                            <th>Data</th>
                            <th>Responsável</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($logs as $l): ?>
                        <tr>
                            <td><code class="text-muted small"><?= htmlspecialchars($l['old_dns']) ?></code></td>
                            <td><strong class="text-primary small"><?= htmlspecialchars($l['new_dns']) ?></strong></td>
                            <td><small class="text-muted"><?= $l['migration_date'] ?></small></td>
                            <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($l['migrated_by']) ?></span></td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(!$logs): ?>
                        <tr><td colspan="4" class="text-center py-4 text-muted">Nenhum log encontrado.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    // Fechamento automático de alertas
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(() => {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(a => {
                const bsAlert = new bootstrap.Alert(a);
                bsAlert.close();
            });
        }, 4000);
    });
</script>

<?php if(file_exists('includes/footer.php')) include 'includes/footer.php'; ?>