<?php

/**
 * Load all zone names from named.conf-style file.
 *
 * @param string $namedConfPath
 * @return array
 */
function load_zones(string $namedConfPath): array {
    $zones = [];
    $lines = @file($namedConfPath);

    if (!$lines) {
        return [];
    }

    foreach ($lines as $line) {
        if (preg_match('/zone\s+"([^"]+)"/', $line, $m)) {
            $zones[] = $m[1];
        }
    }

    return $zones;
}

/**
 * Load a zonefile's contents.
 *
 * @param string $zoneDir
 * @param string $zone
 * @return string|false
 */
function load_zonefile(string $zoneDir, string $zone) {
    $file = "$zoneDir/$zone.hosts";

    if (!file_exists($file)) {
        return false;
    }

    return file_get_contents($file);
}

/**
 * Save zonefile contents.
 *
 * @param string $zoneDir
 * @param string $zone
 * @param string $content
 * @return bool
 */
function save_zonefile(string $zoneDir, string $zone, string $content): bool {
    $file = "$zoneDir/$zone.hosts";
    return file_put_contents($file, $content) !== false;
}

/**
 * Parse SOA record from zonefile.
 */
function parse_soa(string $content): array {
    $soa = [
        'primary'   => '',
        'hostmaster'=> '',
        'serial'    => '',
        'refresh'   => '',
        'retry'     => '',
        'expire'    => '',
        'minimum'   => ''
    ];

    if (preg_match('/SOA\s+(\S+)\s+(\S+)\s+\(\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s*\)/i', $content, $m)) {
        $soa['primary']    = $m[1];
        $soa['hostmaster'] = $m[2];
        $soa['serial']     = $m[3];
        $soa['refresh']    = $m[4];
        $soa['retry']      = $m[5];
        $soa['expire']     = $m[6];
        $soa['minimum']    = $m[7];
    }

    return $soa;
}

/**
 * Parse DNS records from zonefile.
 */
function parse_records(string $content): array {
    $records = [];
    $lines = explode("\n", $content);

    foreach ($lines as $line) {
        $line = trim($line);

        // Skip comments and empty lines
        if ($line === '' || str_starts_with($line, ';')) {
            continue;
        }

        // Match generic DNS record format
        if (preg_match('/^(\S+)\s+(\d+)?\s*(IN)?\s+(\S+)\s+(.+)$/i', $line, $m)) {
            $records[] = [
                'name'  => $m[1],
                'ttl'   => $m[2] ?: '',
                'class' => $m[3] ?: 'IN',
                'type'  => $m[4],
                'value' => $m[5]
            ];
        }
    }

    return $records;
}

