<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('X-Powered-By: SiliconPin Tools');
/**
 * DNS A Record Lookup API
 * Endpoint: /dns-tools-get-a-record
 * Method: POST
 * Content-Type: application/json
 */

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

// -------------------------------
// Allow only POST
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Only POST method allowed'
    ]);
    exit;
}

// -------------------------------
// Read JSON body
// -------------------------------
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);

$domain = $data['domain'] ?? '';

// -------------------------------
// Domain validation
// -------------------------------
function validateDomain(string $domain): bool
{
    return (bool) preg_match(
        '/^(?!-)(?:[a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,}$/',
        $domain
    );
}

if (!$domain || !validateDomain($domain)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid domain'
    ]);
    exit;
}

// -------------------------------
// DNS lookup (NO shell_exec)
// -------------------------------
$records = dns_get_record($domain, DNS_A);
$ips = [];

if ($records !== false) {
    foreach ($records as $record) {
        if (!empty($record['ip'])) {
            $ips[] = $record['ip'];
        }
    }
}

// -------------------------------
// Response
// -------------------------------
if (empty($ips)) {
    echo json_encode([
        'success' => false,
        'domain'  => $domain,
        'message' => 'No A records found',
        'ips'     => []
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'domain'  => $domain,
    'ips'     => $ips
]);
