<?php
require_once __DIR__ . '/../.hta_config/conf.php';

applyApiHeaders($API_HEADERS);
handleCorsPreflight();

// -------------------------------
// 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);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid JSON payload'
    ]);
    exit;
}

// -------------------------------
// Normalize domain
// -------------------------------
$domain = trim($data['domain'] ?? '');
$domain = preg_replace('#^https?://#', '', $domain);
$domain = preg_replace('#/.*$#', '', $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 with timing
// -------------------------------
$startTime = microtime(true);
$records = dns_get_record($domain, DNS_A);
$lookupTimeMs = round((microtime(true) - $startTime) * 1000, 2);

// -------------------------------
// Resolver info
// -------------------------------
$resolver = 'hosting-default';

// -------------------------------
// Provider detection (heuristic)
// -------------------------------
function detectProvider(string $ip): string
{
    if (preg_match('/^(104\.|172\.6[4-7]\.)/', $ip)) {
        return 'Cloudflare';
    }
    if (preg_match('/^(13\.|15\.|52\.|54\.)/', $ip)) {
        return 'AWS';
    }
    if (preg_match('/^(34\.|35\.)/', $ip)) {
        return 'Google Cloud';
    }
    return 'Unknown';
}

// -------------------------------
// Build records
// -------------------------------
$result = [];

if ($records !== false) {
    foreach ($records as $record) {
        if (!empty($record['ip'])) {
            $result[] = [
                'ip'       => $record['ip'],
                'ttl'      => $record['ttl'] ?? null,
                'provider' => detectProvider($record['ip'])
            ];
        }
    }
}

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

echo json_encode([
    'success'         => true,
    'domain'          => $domain,
    'record_count'    => count($result),
    'lookup_time_ms'  => $lookupTimeMs,
    'resolver'        => $resolver,
    'records'         => $result
]);
