<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_admin();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    verify_csrf();

    $action = (string)($_POST['action'] ?? '');

    try {
        if ($action === 'save') {
            $id = (int)($_POST['id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            $url = normalize_url((string)($_POST['url'] ?? ''));
            $priority = max(1, (int)($_POST['priority'] ?? 100));
            $active = (int)($_POST['active'] ?? 0) === 1 ? 1 : 0;
            $authorized = (int)($_POST['authorized'] ?? 0) === 1 ? 1 : 0;

            if ($name === '' || !$url) {
                throw new RuntimeException(
                    'Informe um nome e uma URL válida.'
                );
            }

            if ($id > 0) {
                $stmt = db()->prepare(
                    'UPDATE servers
                     SET name = ?,
                         url = ?,
                         active = ?,
                         authorized = ?,
                         priority = ?,
                         updated_at = ?
                     WHERE id = ?'
                );

                $stmt->execute([
                    $name,
                    $url,
                    $active,
                    $authorized,
                    $priority,
                    now(),
                    $id
                ]);

                flash('success', 'DNS atualizada com sucesso.');
            } else {
                $stmt = db()->prepare(
                    'INSERT INTO servers
                    (
                        name,
                        url,
                        active,
                        authorized,
                        priority,
                        created_at,
                        updated_at
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?)'
                );

                $stmt->execute([
                    $name,
                    $url,
                    $active,
                    $authorized,
                    $priority,
                    now(),
                    now()
                ]);

                flash('success', 'DNS cadastrada com sucesso.');
            }
        } elseif ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Servidor inválido.');
            }

            $stmt = db()->prepare(
                'DELETE FROM servers WHERE id = ?'
            );

            $stmt->execute([$id]);

            flash('success', 'DNS removida com sucesso.');
        } elseif ($action === 'test') {
            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Servidor invalido.');
            }

            $stmt = db()->prepare('SELECT * FROM servers WHERE id = ?');
            $stmt->execute([$id]);
            $server = $stmt->fetch();
            if (!$server) {
                throw new RuntimeException('Servidor nao encontrado.');
            }

            [$status, $message] = test_dns_connection((string)$server['url']);
            $update = db()->prepare('UPDATE servers SET last_test_at=?, last_test_status=?, last_test_message=?, updated_at=? WHERE id=?');
            $update->execute([now(), $status, $message, now(), $id]);

            flash($status === 'online' ? 'success' : 'error', 'Teste da DNS ' . $server['name'] . ': ' . $status . ' (' . $message . ').');
        }
    } catch (Throwable $e) {
        $message =
            $e instanceof PDOException
            && stripos($e->getMessage(), 'UNIQUE') !== false
                ? 'Esta URL já está cadastrada.'
                : $e->getMessage();

        flash('error', $message);
    }

    redirect('dns.php');
}

$edit = null;

if (!empty($_GET['edit'])) {
    $stmt = db()->prepare(
        'SELECT * FROM servers WHERE id = ?'
    );

    $stmt->execute([
        (int)$_GET['edit']
    ]);

    $edit = $stmt->fetch() ?: null;
}

$servers = db()->query(
    'SELECT *
     FROM servers
     ORDER BY priority ASC, name ASC'
)->fetchAll();

$pageTitle = 'Conexões DNS';
$pageSubtitle =
    'Cadastre e organize os servidores utilizados pelo aplicativo.';
$pageIcon = 'fa-server';

require __DIR__ . '/includes/header.php';
?>

<style>
.dns-actions {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    flex-wrap: nowrap;
}

.dns-actions form {
    display: inline-flex;
    margin: 0;
    padding: 0;
}

.dns-icon-button {
    width: 42px;
    height: 42px;
    min-width: 42px;
    padding: 0 !important;
    display: inline-flex !important;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
}

.dns-icon-button i {
    margin: 0 !important;
    font-size: 15px;
}

.dns-order {
    text-align: center;
    font-weight: 700;
}

.dns-actions-column {
    width: 110px;
    min-width: 110px;
    text-align: center;
}

.dns-url code {
    white-space: normal;
    overflow-wrap: anywhere;
    word-break: break-word;
}

@media (max-width: 768px) {
    .dns-actions {
        justify-content: flex-start;
    }
}
</style>

<div class="split-grid">

    <section class="panel-card">

        <div class="panel-card-head">
            <div class="panel-card-icon">
                <i class="fa-solid fa-server"></i>
            </div>

            <div>
                <h2>
                    <?= $edit
                        ? 'Editar conexão'
                        : 'Nova conexão'
                    ?>
                </h2>

                <p>
                    A prioridade define a ordem dos servidores
                    utilizados pelo aplicativo.
                </p>
            </div>
        </div>

        <form method="post">

            <input
                type="hidden"
                name="csrf"
                value="<?= e(csrf_token()) ?>"
            >

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                value="<?= e($edit['id'] ?? '') ?>"
            >

            <div
                class="form-grid"
                style="grid-template-columns: 1fr"
            >

                <div class="form-field">
                    <label for="name">
                        Nome de exibição
                    </label>

                    <input
                        id="name"
                        name="name"
                        value="<?= e($edit['name'] ?? '') ?>"
                        placeholder="Servidor principal"
                        required
                    >
                </div>

                <div class="form-field">
                    <label for="url">
                        URL/DNS completa
                    </label>

                    <input
                        id="url"
                        name="url"
                        value="<?= e($edit['url'] ?? '') ?>"
                        placeholder="http://servidor.com:8080"
                        required
                    >

                    <small>
                        Use somente a base do servidor,
                        sem player_api.php.
                    </small>
                </div>

                <div class="form-field">
                    <label for="priority">
                        Ordem de prioridade
                    </label>

                    <input
                        id="priority"
                        name="priority"
                        type="number"
                        min="1"
                        value="<?= e($edit['priority'] ?? 1) ?>"
                        required
                    >

                    <small>
                        O número 1 será o servidor principal.
                    </small>
                </div>

                <div class="form-field">
                    <label for="active">
                        Status administrativo
                    </label>

                    <select id="active" name="active">
                        <option
                            value="1"
                            <?= (
                                (int)($edit['active'] ?? 1) === 1
                            ) ? 'selected' : '' ?>
                        >
                            Ativo
                        </option>

                        <option
                            value="0"
                            <?= (
                                (int)($edit['active'] ?? 1) === 0
                            ) ? 'selected' : '' ?>
                        >
                            Desativado
                        </option>
                    </select>
                </div>

                <div class="form-field">
                    <label for="authorized">
                        Autorização no aplicativo
                    </label>

                    <select
                        id="authorized"
                        name="authorized"
                    >
                        <option
                            value="1"
                            <?= (
                                (int)($edit['authorized'] ?? 1) === 1
                            ) ? 'selected' : '' ?>
                        >
                            Autorizado
                        </option>

                        <option
                            value="0"
                            <?= (
                                (int)($edit['authorized'] ?? 1) === 0
                            ) ? 'selected' : '' ?>
                        >
                            Bloqueado
                        </option>
                    </select>
                </div>

            </div>

            <div
                class="form-actions"
                style="position: static; margin: 0 20px 20px"
            >

                <button
                    class="button primary"
                    type="submit"
                >
                    <i class="fa-solid fa-floppy-disk"></i>

                    <?= $edit
                        ? 'Atualizar DNS'
                        : 'Cadastrar DNS'
                    ?>
                </button>

                <?php if ($edit): ?>
                    <a
                        class="button ghost"
                        href="<?= e(panel_url('dns.php')) ?>"
                    >
                        <i class="fa-solid fa-xmark"></i>
                        Cancelar
                    </a>
                <?php endif; ?>

            </div>

        </form>

    </section>

    <section class="panel-card">

        <div class="panel-card-head">
            <div class="panel-card-icon">
                <i class="fa-solid fa-list"></i>
            </div>

            <div>
                <h2>Servidores cadastrados</h2>

                <p>
                    <?= count($servers) ?>
                    conexão(ões) encontrada(s).
                </p>
            </div>
        </div>

        <?php if (!$servers): ?>

            <div class="empty-state">
                <i class="fa-solid fa-server"></i>
                Nenhuma DNS cadastrada.
            </div>

        <?php else: ?>

            <div class="table-wrap">

                <table class="data-table">

                    <thead>
                        <tr>
                            <th>Ordem</th>
                            <th>Servidor</th>
                            <th>URL</th>
                            <th>Ultimo teste</th>
                            <th>Liberação</th>
                            <th class="dns-actions-column">
                                Ações
                            </th>
                        </tr>
                    </thead>

                    <tbody>

                    <?php foreach ($servers as $server): ?>

                        <?php
                        $released =
                            (int)$server['active'] === 1
                            && (int)$server['authorized'] === 1;
                        ?>

                        <tr>

                            <td class="dns-order">
                                <?= e($server['priority']) ?>
                            </td>

                            <td>
                                <strong>
                                    <?= e($server['name']) ?>
                                </strong>

                                <br>

                                <small class="muted">
                                    ID #<?= e($server['id']) ?>
                                </small>
                            </td>

                            <td class="dns-url">
                                <code>
                                    <?= e($server['url']) ?>
                                </code>
                            </td>

                            <td>
                                <?php
                                $testStatus = (string)($server['last_test_status'] ?? '');
                                $testClass = $testStatus === 'online' ? 'active' : 'inactive';
                                ?>
                                <?php if ($testStatus !== ''): ?>
                                    <span class="badge <?= e($testClass) ?>"><?= e($testStatus) ?></span>
                                    <br>
                                    <small class="muted"><?= e($server['last_test_message'] ?? '') ?></small>
                                    <br>
                                    <small class="muted"><?= e($server['last_test_at'] ?? '') ?></small>
                                <?php else: ?>
                                    <small class="muted">Ainda nao testado</small>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span
                                    class="badge <?= $released
                                        ? 'active'
                                        : 'inactive'
                                    ?>"
                                >
                                    <?= $released
                                        ? 'Liberado'
                                        : 'Bloqueado'
                                    ?>
                                </span>
                            </td>

                            <td class="dns-actions-column">

                                <div class="dns-actions">

                                    <a
                                        class="button ghost dns-icon-button"
                                        href="<?= e(
                                            panel_url(
                                                'dns.php?edit='
                                                . (int)$server['id']
                                            )
                                        ) ?>"
                                        title="Editar DNS"
                                        aria-label="Editar DNS"
                                    >
                                        <i class="fa-solid fa-pen"></i>
                                    </a>

                                    <form method="post">
                                        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                        <input type="hidden" name="action" value="test">
                                        <input type="hidden" name="id" value="<?= e($server['id']) ?>">
                                        <button class="button ghost dns-icon-button" type="submit" title="Testar DNS" aria-label="Testar DNS">
                                            <i class="fa-solid fa-plug-circle-check"></i>
                                        </button>
                                    </form>

                                    <form
                                        method="post"
                                        onsubmit="
                                            return confirm(
                                                'Excluir esta DNS?'
                                            );
                                        "
                                    >
                                        <input
                                            type="hidden"
                                            name="csrf"
                                            value="<?= e(csrf_token()) ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="delete"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= e($server['id']) ?>"
                                        >

                                        <button
                                            class="button danger dns-icon-button"
                                            type="submit"
                                            title="Excluir DNS"
                                            aria-label="Excluir DNS"
                                        >
                                            <i
                                                class="fa-solid fa-trash"
                                            ></i>
                                        </button>
                                    </form>

                                </div>

                            </td>

                        </tr>

                    <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

        <?php endif; ?>

    </section>

</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
