<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

// Verificar se o usuário está logado
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Não autenticado']);
    exit;
}

try {
    $dbPath = __DIR__ . '/../ibo_panel.db';
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $input = json_decode(file_get_contents('php://input'), true);
    if (!is_array($input)) {
        $input = [];
    }

    $action = $input['action'] ?? 'view';

    if ($action === 'view') {
        $stmt = $db->query("SELECT * FROM dns ORDER BY id ASC");
        $dnsRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $dnsRecords]);
        exit;
    }

    if ($action === 'add') {
        $title = trim((string)($input['title'] ?? ''));
        $url   = trim((string)($input['url'] ?? ''));

        if ($title === '' || $url === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Título e URL são obrigatórios']);
            exit;
        }

        $stmt = $db->prepare("INSERT INTO dns (title, url) VALUES (:title, :url)");
        $stmt->execute([':title' => $title, ':url' => $url]);

        echo json_encode(['success' => true, 'message' => 'DNS adicionado', 'new_id' => $db->lastInsertId()]);
        exit;
    }

    if ($action === 'edit') {
        $id    = (int)($input['id'] ?? 0);
        $title = trim((string)($input['title'] ?? ''));
        $url   = trim((string)($input['url'] ?? ''));

        if ($id <= 0 || $title === '' || $url === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Parâmetros inválidos']);
            exit;
        }

        $check = $db->prepare("SELECT COUNT(*) FROM dns WHERE id = :id");
        $check->execute([':id' => $id]);
        if ((int)$check->fetchColumn() === 0) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'DNS não encontrado']);
            exit;
        }

        $stmt = $db->prepare("UPDATE dns SET title = :title, url = :url WHERE id = :id");
        $stmt->execute([':id' => $id, ':title' => $title, ':url' => $url]);

        echo json_encode(['success' => true, 'message' => 'DNS atualizado']);
        exit;
    }

    if ($action === 'delete') {
        $id = (int)($input['id'] ?? 0);

        if ($id <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID inválido']);
            exit;
        }

        // Protege o DNS principal (ID = 1)
        if ($id === 1) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'O DNS Principal (ID 1) não pode ser apagado!']);
            exit;
        }

        $check = $db->prepare("SELECT COUNT(*) FROM dns WHERE id = :id");
        $check->execute([':id' => $id]);
        if ((int)$check->fetchColumn() === 0) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'DNS não encontrado']);
            exit;
        }

        // 1) Apaga o registro
        $stmt = $db->prepare("DELETE FROM dns WHERE id = :id");
        $stmt->execute([':id' => $id]);

        // 2) Reajusta sqlite_sequence (só se existir)
        $seqExists = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'")->fetchColumn();
        if ($seqExists) {
            $stmtMax = $db->query("SELECT MAX(id) as max_id FROM dns");
            $row = $stmtMax->fetch(PDO::FETCH_ASSOC);
            $newSeq = ($row && $row['max_id'] !== null) ? (int)$row['max_id'] : 0;

            $stmtSeq = $db->prepare("UPDATE sqlite_sequence SET seq = :new_seq WHERE name = 'dns'");
            $stmtSeq->execute([':new_seq' => $newSeq]);
        }

        echo json_encode(['success' => true, 'message' => 'DNS eliminado e ID ajustado']);
        exit;
    }

    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Ação inválida']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erro: ' . $e->getMessage()]);
}
