<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'add') {
            $stmt = db()->prepare(
                'INSERT INTO dns_servers (name, server_url, username, password, is_active, priority)
                 VALUES (?, ?, NULL, NULL, ?, ?)'
            );
            $stmt->execute([
                trim($_POST['name']),
                rtrim(trim($_POST['server_url']), '/'),
                isset($_POST['is_active']) ? 1 : 0,
                (int) ($_POST['priority'] ?? 0),
            ]);
            flash('success', 'Servidor DNS adicionado.');
        } elseif ($action === 'delete') {
            $stmt = db()->prepare('DELETE FROM dns_servers WHERE id = ?');
            $stmt->execute([(int) $_POST['id']]);
            flash('success', 'Servidor removido.');
        } elseif ($action === 'toggle') {
            $stmt = db()->prepare('UPDATE dns_servers SET is_active = NOT is_active WHERE id = ?');
            $stmt->execute([(int) $_POST['id']]);
            flash('success', 'Status atualizado.');
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
    header('Location: dns.php');
    exit;
}

$servers = db()->query('SELECT * FROM dns_servers ORDER BY priority ASC, id ASC')->fetchAll();
$activeCount = count(array_filter($servers, function ($s) { return (int) $s['is_active'] === 1; }));

render_header(
    'DNS Xtream',
    'dns',
    'Servidores globais compartilhados por todos os dispositivos',
    [
        ['label' => 'Dashboard', 'url' => 'dashboard.php'],
        ['label' => 'DNS Xtream', 'url' => null],
    ]
);
?>

<div class="content-split dns-page">
    <div class="content-main">
        <div class="card card-flush">
            <div class="card-header">
                <div>
                    <h2>Servidores cadastrados</h2>
                    <p class="card-desc"><?= (int) $activeCount ?> ativo(s) de <?= count($servers) ?> — o app testa por prioridade até conectar.</p>
                </div>
            </div>
            <div class="table-wrap">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th>URL</th>
                            <th>Prioridade</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($servers as $s): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($s['name']) ?></strong></td>
                            <td class="cell-url"><?= htmlspecialchars($s['server_url']) ?></td>
                            <td><?= (int) $s['priority'] ?></td>
                            <td>
                                <?php if ($s['is_active']): ?>
                                    <span class="status-pill on">Ativo</span>
                                <?php else: ?>
                                    <span class="status-pill off">Inativo</span>
                                <?php endif; ?>
                            </td>
                            <td class="actions-cell">
                                <form method="post">
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
                                    <button type="submit" class="btn secondary btn-sm">Alternar</button>
                                </form>
                                <form method="post" onsubmit="return confirm('Remover servidor?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
                                    <button type="submit" class="btn danger btn-sm">Excluir</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($servers)): ?>
                        <tr><td colspan="5" class="empty-cell">Nenhum servidor cadastrado.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <aside class="content-side">
        <div class="card">
            <h2>Adicionar servidor</h2>
            <p class="card-desc">Cadastre a URL base. Login e senha são informados pelo usuário no app.</p>
            <form method="post">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                    <label>Nome</label>
                    <input type="text" name="name" required placeholder="Servidor Principal">
                </div>
                <div class="form-group">
                    <label>URL Xtream</label>
                    <input type="url" name="server_url" required placeholder="http://servidor.com:8080">
                    <p class="form-hint">Sem /player_api.php</p>
                </div>
                <div class="form-group">
                    <label>Prioridade</label>
                    <input type="number" name="priority" value="0" min="0">
                    <p class="form-hint">Menor número = tentativa primeiro</p>
                </div>
                <label class="toggle-row compact">
                    <input type="checkbox" name="is_active" checked>
                    <div class="toggle-info"><strong>Ativo</strong></div>
                </label>
                <button type="submit" class="btn primary" style="width:100%;margin-top:12px;">Adicionar DNS</button>
            </form>
        </div>
    </aside>
</div><?php render_footer(); ?>
