<?php
session_start(); // Garante que a sessão está ativa para as mensagens
$jsonFile = 'dns.json';

function readDNS() {
    global $jsonFile;
    if (file_exists($jsonFile)) {
        return json_decode(file_get_contents($jsonFile), true) ?: ['portals' => []];
    }
    return ['portals' => []];
}

function saveDNS($data) {
    global $jsonFile;
    return file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

$dnsData = readDNS();
$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';

// --- PROCESSAR DELETAR ---
if ($action == 'delete' && is_numeric($id)) {
    $id = intval($id);
    $portals = $dnsData['portals'];
    $dnsData['portals'] = array_values(array_filter($portals, function($portal) use ($id) {
        return $portal['id'] != $id;
    }));
    
    // Reindexar
    foreach ($dnsData['portals'] as $index => $portal) {
        $dnsData['portals'][$index]['id'] = $index;
    }
    
    saveDNS($dnsData);
    $_SESSION['success_msg'] = "Portal deletado com sucesso!";
    header("Location: dns.php");
    exit();
}

// --- PROCESSAR ADICIONAR/EDITAR ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $postId = $_POST['id'] ?? '';
    $name = trim($_POST['name'] ?? '');
    $url = trim($_POST['url'] ?? '');
    $epg_url = trim($_POST['epg_url'] ?? '');

    if (!empty($name) && !empty($url)) {
        $portals = $dnsData['portals'];
        if ($postId === '') {
            $newId = count($portals);
            $portals[] = ['id' => $newId, 'name' => $name, 'url' => $url, 'epg_url' => $epg_url];
        } else {
            $postId = intval($postId);
            foreach ($portals as $index => $portal) {
                if ($portal['id'] == $postId) {
                    $portals[$index] = ['id' => $postId, 'name' => $name, 'url' => $url, 'epg_url' => $epg_url];
                    break;
                }
            }
        }
        $dnsData['portals'] = $portals;
        saveDNS($dnsData);
        $_SESSION['success_msg'] = "Dados salvos com sucesso!";
        header("Location: dns.php");
        exit();
    }
}

// Buscar dados para edição (apenas após os processos acima)
$editData = [];
if ($action == 'edit' && is_numeric($id)) {
    foreach ($dnsData['portals'] as $portal) {
        if ($portal['id'] == intval($id)) {
            $editData = $portal;
            break;
        }
    }
}

// SÓ AGORA COMEÇA O HTML
include "includes/header.php";
?>

<style>
/* Estilos para a tabela */
.table th {
    background-color: #343a40;
    color: white;
    border: none;
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.1);
}

.badge-status {
    font-size: 0.8em;
    padding: 5px 10px;
}

/* Animação para novos itens */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.fade-in {
    animation: fadeIn 0.5s ease-out;
}
</style>

<div class="container-fluid mt-4">
    <!-- Mensagens de alerta -->
    <?php if (isset($_SESSION['success_msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['success_msg']; ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <?php unset($_SESSION['success_msg']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_msg'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['error_msg']; ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <?php unset($_SESSION['error_msg']); ?>
    <?php endif; ?>

    <div class="row">
        <div class="col-12">
            <div class="card shadow mb-4">
                <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">
                        <i class="fas fa-server mr-2"></i>Gerenciamento de DNS
                    </h4>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#addModal">
                        <i class="fas fa-plus mr-2"></i>Novo Portal
                    </button>
                </div>
                <div class="card-body">
                    <?php if (empty($dnsData['portals'])): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-server fa-4x text-muted mb-3"></i>
                            <h5>Nenhum portal cadastrado</h5>
                            <p class="text-muted">Clique em "Novo Portal" para adicionar seu primeiro servidor DNS.</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive fade-in">
                            <table class="table table-hover">
                                <thead class="thead-dark">
                                    <tr>
                                        <th width="5%">ID</th>
                                        <th width="25%">Nome</th>
                                        <th width="35%">URL</th>
                                        <th width="25%">EPG URL</th>
                                        <th width="10%" class="text-center">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($dnsData['portals'] as $portal): ?>
                                    <tr>
                                        <td><span class="badge badge-info"><?php echo $portal['id']; ?></span></td>
                                        <td><strong><?php echo htmlspecialchars($portal['name']); ?></strong></td>
                                        <td>
                                            <a href="<?php echo htmlspecialchars($portal['url']); ?>" target="_blank" class="text-truncate d-inline-block" style="max-width: 300px;">
                                                <?php echo htmlspecialchars($portal['url']); ?>
                                            </a>
                                        </td>
                                        <td>
                                            <?php if (!empty($portal['epg_url'])): ?>
                                            <a href="<?php echo htmlspecialchars($portal['epg_url']); ?>" target="_blank" class="text-truncate d-inline-block" style="max-width: 250px;">
                                                <?php echo htmlspecialchars($portal['epg_url']); ?>
                                            </a>
                                            <?php else: ?>
                                            <span class="text-muted">Não configurado</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <div class="btn-group" role="group">
                                                <button onclick="editPortal(<?php echo $portal['id']; ?>)" class="btn btn-sm btn-warning" title="Editar">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button onclick="confirmDelete(<?php echo $portal['id']; ?>, '<?php echo htmlspecialchars(addslashes($portal['name'])); ?>')" class="btn btn-sm btn-danger" title="Excluir">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="mt-3 text-muted">
                            <small><i class="fas fa-info-circle mr-1"></i>Total de portais: <?php echo count($dnsData['portals']); ?></small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para Adicionar/Editar -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST" action="">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title" id="addModalLabel">
                        <?php echo empty($editData) ? '<i class="fas fa-plus mr-2"></i>Adicionar Novo Portal' : '<i class="fas fa-edit mr-2"></i>Editar Portal'; ?>
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="id" value="<?php echo $editData['id'] ?? ''; ?>">
                    
                    <div class="form-group">
                        <label for="name"><i class="fas fa-font mr-1"></i>Nome do Portal *</label>
                        <input type="text" class="form-control" id="name" name="name" 
                               value="<?php echo htmlspecialchars($editData['name'] ?? ''); ?>" 
                               placeholder="Ex: MAX REBRANDS" required>
                        <small class="form-text text-muted">Nome descritivo para o portal</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="url"><i class="fas fa-link mr-1"></i>URL do Portal *</label>
                        <input type="url" class="form-control" id="url" name="url" 
                               value="<?php echo htmlspecialchars($editData['url'] ?? ''); ?>" 
                               placeholder="Ex: http://seuservidor.com" required>
                        <small class="form-text text-muted">Endereço completo do servidor DNS</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="epg_url"><i class="fas fa-tv mr-1"></i>URL do EPG (Opcional)</label>
                        <input type="url" class="form-control" id="epg_url" name="epg_url" 
                               value="<?php echo htmlspecialchars($editData['epg_url'] ?? ''); ?>" 
                               placeholder="Ex: https://epg.seuservidor.com/guide.xml">
                        <small class="form-text text-muted">Link para o guia de programação eletrônica</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i>
                        <?php echo empty($editData) ? 'Adicionar Portal' : 'Salvar Alterações'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Função para confirmar exclusão
function confirmDelete(id, name) {
    if (confirm(`Tem certeza que deseja excluir o portal "${name}"?`)) {
        window.location.href = `dns.php?action=delete&id=${id}`;
    }
}

// Função para editar portal
function editPortal(id) {
    window.location.href = `dns.php?action=edit&id=${id}`;
}

// Auto-abrir modal se estiver editando
<?php if (!empty($editData)): ?>
$(document).ready(function() {
    $('#addModal').modal('show');
});
<?php endif; ?>

// Validar URL antes de enviar
document.querySelector('form').addEventListener('submit', function(e) {
    const urlField = document.getElementById('url');
    const urlValue = urlField.value.trim();
    
    if (urlValue && !urlValue.startsWith('http://') && !urlValue.startsWith('https://')) {
        alert('A URL deve começar com http:// ou https://');
        urlField.focus();
        e.preventDefault();
    }
});

// Limpar formulário quando modal for fechado
$('#addModal').on('hidden.bs.modal', function () {
    window.location.href = 'dns.php';
});
</script>

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