<?php
require_once '../../config.php'; // Ensure database connection is available
require_once 'Net/DNS2.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = trim($_POST['host']);
    $dnsZone = isset($_POST['dnsZone']) ? trim($_POST['dnsZone']) : null;

    if (empty($host)) {
        echo json_encode(['success' => 0, 'message' => 'Invalid host value.']);
        exit;
    }

    // Determine if the input is an IP or a domain
    $is_ip = filter_var($host, FILTER_VALIDATE_IP);

    if ($dnsZone === null) {
        // Fetch DNSBL zones based on the type (IP or Host)
        $type = $is_ip ? 'IP' : 'Host';
        $dnsbl_query = "SELECT name, dnszone, url FROM evp_dnsbl WHERE type = '$type'";
        $dnsbl_result = $db->select($dnsbl_query);

        if ($dnsbl_result->num_rows === 0) {
            echo json_encode(['success' => 0, 'message' => 'No DNSBL zones found in the database for the given type.']);
            exit;
        }

        $dnsZones = [];
        while ($dnsbl = $dnsbl_result->fetch_assoc()) {
            $dnsZones[] = $dnsbl;
        }

        echo json_encode(['success' => 1, 'result' => $dnsZones]);
        exit;
    } else {
        // Process individual DNSBL zone
        $resolver = new Net_DNS2_Resolver(['nameservers' => ['208.67.222.222']]);
        $reverse_ip = implode('.', array_reverse(explode('.', gethostbyname($host))));
        $dnsr = $is_ip ? $reverse_ip . '.' . $dnsZone : $host . '.' . $dnsZone;

        $listed = false;
        $a_data = null;
        $txt_data = null;

        try {
            $response = $resolver->query($dnsr, "A");
            if (count($response->answer) > 0) {
                $a_data = $response->answer[0]->address;
                $listed = true;
            }

            $response = $resolver->query($dnsr, "TXT");
            if (count($response->answer) > 0) {
                $txt_data = $response->answer[0]->text[0];
                $listed = true;
            }
        } catch (Net_DNS2_Exception $e) {
            // Handle DNS query exceptions
        }

        $status = $listed ? "Listed" : "Not Listed";

        echo json_encode([
            'success' => 1,
            'result' => [
                'name' => $dnsZone,
                'host' => $dnsZone,
                'url' => '', // Add URL if available
                'listed' => $status,
                'a_r' => $a_data,
                'txt_r' => $txt_data
            ]
        ]);
        exit;
    }
}
?>