<?php
declare(strict_types=1);

$pageTitle = 'DNS';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    $action = (string)($_POST['action'] ?? 'save_dns');

    if ($action === 'bulk_replace_dns') {
        $from = rtrim(gpc_base_url((string)($_POST['from_dns'] ?? '')), '/');
        $to = rtrim(gpc_base_url((string)($_POST['to_dns'] ?? '')), '/');
        $scope = (string)($_POST['scope'] ?? 'devices');
        if ($from === '' || $to === '' || $from === $to) {
            gpc_flash('bad', 'Informe a DNS antiga e a nova DNS corretamente.');
        } else {
            try {
                $db->beginTransaction();
                $changedDevices = 0;
                $changedDns = 0;
                if ($scope === 'devices' || $scope === 'all') {
                    $rows = $db->query('SELECT id,dns,playlist_url FROM devices')->fetchAll();
                    $upd = $db->prepare('UPDATE devices SET dns=:dns, playlist_url=:pl WHERE id=:id');
                    foreach ($rows as $row) {
                        $oldDns = rtrim((string)($row['dns'] ?? ''), '/');
                        $oldPl = (string)($row['playlist_url'] ?? '');
                        $newDns = ($oldDns !== '' && gpc_base_url($oldDns) === $from) ? $to : (string)($row['dns'] ?? '');
                        $newPl = str_replace([$from, $from.'/'], [$to, $to.'/'], $oldPl);
                        if ($newDns !== (string)($row['dns'] ?? '') || $newPl !== $oldPl) {
                            $upd->execute([':dns'=>$newDns, ':pl'=>$newPl, ':id'=>(int)$row['id']]);
                            $changedDevices++;
                        }
                    }
                }
                if ($scope === 'dns' || $scope === 'all') {
                    $rows = $db->query('SELECT id,url FROM dns_servers')->fetchAll();
                    $updDns = $db->prepare('UPDATE dns_servers SET url=:u WHERE id=:id');
                    foreach ($rows as $row) {
                        $oldUrl = rtrim((string)$row['url'], '/');
                        if (gpc_base_url($oldUrl) === $from) {
                            $updDns->execute([':u'=>$to, ':id'=>(int)$row['id']]);
                            $changedDns++;
                        }
                    }
                }
                $db->commit();
                gpc_flash('ok', 'Troca em massa concluída. Listas/MACs alterados: '.$changedDevices.'. DNS cadastradas alteradas: '.$changedDns.'.');
            } catch (Throwable $e) {
                if ($db->inTransaction()) $db->rollBack();
                gpc_flash('bad', 'Erro na troca em massa: '.$e->getMessage());
            }
        }
        header('Location: ' . $self);
        exit;
    }

    $id = (int) ($_POST['id'] ?? 0);
    $name = trim((string) ($_POST['name'] ?? ''));
    $url = trim((string) ($_POST['url'] ?? ''));
    $code = trim((string) ($_POST['code'] ?? ''));
    $status = (int) ($_POST['status'] ?? 1);
    $validity = trim((string) ($_POST['validity'] ?? ''));

    if ($name === '' || $url === '') {
        gpc_flash('bad', 'Preencha os campos obrigatórios');
    } elseif ($id > 0) {
        $db->prepare('UPDATE dns_servers SET name=:n, url=:u, code=:c, status=:s, validity=:v WHERE id=:id')
            ->execute([':n' => $name, ':u' => $url, ':c' => $code, ':s' => $status, ':v' => $validity, ':id' => $id]);
        gpc_flash('ok', 'Atualizado');
    } else {
        $db->prepare('INSERT INTO dns_servers (name, url, code, status, validity) VALUES (:n, :u, :c, :s, :v)')
            ->execute([':n' => $name, ':u' => $url, ':c' => $code, ':s' => $status, ':v' => $validity]);
        gpc_flash('ok', 'Adicionado');
    }
    header('Location: ' . $self);
    exit;
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $db->prepare('DELETE FROM dns_servers WHERE id = :id')->execute([':id' => (int) $_GET['delete']]);
    gpc_flash('ok', 'Removido');
    header('Location: ' . $self);
    exit;
}

$edit = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $db->prepare('SELECT * FROM dns_servers WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['edit']]);
    $edit = $stmt->fetch() ?: null;
}

$rows = $db->query('SELECT ds.*, r.name AS reseller_name, r.active AS reseller_active, r.validity AS reseller_validity FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id ORDER BY ds.id ASC')->fetchAll();
$csrf = gpc_csrf_token();
?>

<div class="card">
    <div class="card-head">
        <h2><?= $edit ? 'Editar' : 'Adicionar' ?></h2>
        <?php if ($edit): ?><a href="dns.php" class="btn btn-sm btn-ghost">Cancelar</a><?php endif; ?>
    </div>
    <div class="card-body">
        <form method="post">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">
            <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
            <div class="form-grid">
                <div class="field">
                    <label>Nome</label>
                    <input type="text" name="name" required value="<?= gpc_h($edit['name'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>URL</label>
                    <input type="url" name="url" required placeholder="http://servidor:8080"
                           value="<?= gpc_h($edit['url'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>Código DNS (Ex: 0001)</label>
                    <input type="text" name="code" value="<?= gpc_h($edit['code'] ?? '') ?>">
                </div>
                <div class="field">
                    <label>Status</label>
                    <select name="status">
                        <option value="1" <?= ($edit['status'] ?? 1) == 1 ? 'selected' : '' ?>>Ativo</option>
                        <option value="0" <?= ($edit['status'] ?? 1) == 0 ? 'selected' : '' ?>>Inativo</option>
                    </select>
                </div>
                <div class="field">
                    <label>Validade (Opcional)</label>
                    <input type="date" name="validity" value="<?= gpc_h($edit['validity'] ?? '') ?>">
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn"><i data-lucide="check"></i> Salvar</button>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body flush">
        <div class="table-scroll">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nome</th>
                        <th>URL</th>
                        <th>Código</th>
                        <th>Dono</th>
                        <th>Status</th>
                        <th>Validade</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $r): ?>
                    <tr>
                        <td><?= (int) $r['id'] ?></td>
                        <td><?= gpc_h($r['name']) ?></td>
                        <td><code><?= gpc_h($r['url']) ?></code></td>
                        <td><span class="badge"><?= gpc_h($r['code'] ?: '-') ?></span></td>
                        <td><?= $r['reseller_id'] ? gpc_h($r['reseller_name'] ?: 'Revenda #'.(int)$r['reseller_id']) : 'Admin/Master' ?></td>
                        <td>
                            <?php
                            $ownerOk = empty($r['reseller_id']) || ((int)($r['reseller_active'] ?? 0) === 1 && (empty($r['reseller_validity']) || !gpc_expired((string)$r['reseller_validity'])));
                            $dnsOk = ((int)$r['status'] === 1) && (empty($r['validity']) || !gpc_expired((string)$r['validity']));
                            $effectiveOk = $ownerOk && $dnsOk;
                            ?>
                            <?php if ($effectiveOk): ?>
                                <span class="badge badge-success">Ativo</span>
                            <?php else: ?>
                                <span class="badge badge-danger"><?= !$ownerOk ? 'Bloqueada pela revenda' : (((int)$r['status'] !== 1) ? 'Desativada' : 'Vencida') ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php 
                            if ($r['validity']) {
                                $expired = gpc_expired($r['validity']);
                                echo '<span class="'.($expired ? 'text-danger' : '').'">'.date('d/m/Y', strtotime($r['validity'])).'</span>';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td class="row-actions">
                            <a class="btn btn-sm btn-ghost btn-icon" href="?edit=<?= (int) $r['id'] ?>">
                                <i data-lucide="pencil"></i>
                            </a>
                            <a class="btn btn-sm btn-danger btn-icon" href="?delete=<?= (int) $r['id'] ?>"
                               data-confirm="Remover?">
                                <i data-lucide="trash-2"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$rows): ?>
                    <tr><td colspan="8" class="empty">Nenhum servidor</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


<div class="card">
    <div class="card-head"><h2>Troca de DNS em Massa</h2></div>
    <div class="card-body">
        <form method="post">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">
            <input type="hidden" name="action" value="bulk_replace_dns">
            <div class="form-grid">
                <div class="field"><label>DNS antiga</label><input type="text" name="from_dns" placeholder="http://servidor-antigo:80" required></div>
                <div class="field"><label>DNS nova</label><input type="text" name="to_dns" placeholder="http://servidor-novo:80" required></div>
                <div class="field"><label>Aplicar em</label><select name="scope"><option value="devices">Somente MACs/Listas já cadastradas</option><option value="dns">Somente DNS cadastradas no painel</option><option value="all">Tudo: MACs/Listas + DNS cadastradas</option></select></div>
            </div>
            <div class="form-actions"><button type="submit" class="btn" data-confirm="Confirmar troca de DNS em massa?"><i data-lucide="repeat"></i> Trocar DNS em massa</button></div>
            <p class="muted">Use quando uma DNS trocar de domínio/porta. O sistema atualiza as listas salvas e reconstrói os links M3U quando encontrar a DNS antiga.</p>
        </form>
    </div>
</div>

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