<?php
require_once __DIR__ . '/../lib/bootstrap.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', '/tmp/listdns-error.log');
error_reporting(E_ALL);

header('Content-Type: text/html');

/********************************************************************
 * CONFIG
 ********************************************************************/
$namedConfPath = '/etc/named.rfc1912.zones';
$zoneDir       = '/var/named/chroot/var/named';

/********************************************************************
 * LOAD ZONES
 ********************************************************************/
$zones = [];
$namedConf = @file($namedConfPath);

if (!$namedConf) {
    echo "<div class='dns-error'>Cannot read $namedConfPath</div>";
    exit;
}

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

/********************************************************************
 * CSS + JS
 ********************************************************************/
echo <<<HTML
<style>
.dns-wrapper { max-width: 1100px; margin: 0 auto; padding: 10px 20px; }
.dns-domain-list { max-width: 900px; margin: 0 auto; }
.dns-domain-item {
    display: flex; justify-content: space-between; align-items: center;
    background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px;
    padding: 8px 12px; margin-bottom: 6px;
}
.dns-domain-name { font-weight: 600; color: #111827; }
.btn-edit {
    background: #2563eb; color: #fff; border: none; border-radius: 4px;
    padding: 6px 10px; cursor: pointer;
}
.btn-edit:hover { background: #1d4ed8; }
.dns-zone-editor {
    max-width: 900px; margin: 20px auto; background: #ffffff;
    border: 1px solid #d1d5db; border-radius: 6px; padding: 16px;
}
.btn-save {
    background: #16a34a; color: #fff; border: none; border-radius: 4px;
    padding: 8px 12px; margin-top: 10px; cursor: pointer;
}
.btn-save:hover { background: #15803d; }
.dns-success {
    padding: 8px 10px; background: #dcfce7; border: 1px solid #bbf7d0;
    color: #166534; border-radius: 6px; margin-top: 8px;
}
.dns-error {
    padding: 8px 10px; background: #fee2e2; border: 1px solid #fecaca;
    color: #b91c1c; border-radius: 6px; margin-top: 8px;
}
.btn-restore {
    background: #f59e0b;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 8px 12px;
    margin-left: 8px;
    cursor: pointer;
}
.btn-restore:hover { background: #d97706; }
</style>

<script>
function restoreLatestBackup() {
    const zoneInput = document.querySelector('input[name="savezone"]');
    if (!zoneInput) {
        alert('No zone selected.');
        return;
    }
    const zone = zoneInput.value;

    fetch('restorezone.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'restorezone=' + encodeURIComponent(zone)
    })
    .then(response => response.text())
    .then(html => {
        const editor = document.querySelector('.dns-zone-editor');
        if (editor) editor.innerHTML = html;
    })
    .catch(err => alert('Restore failed: ' + err));
}
</script>
HTML;

echo "<div class='dns-wrapper'>";

/********************************************************************
 * 1️⃣ SAVE ZONE
 ********************************************************************/
if (isset($_POST['savezone'])) {

    $zone     = basename($_POST['savezone']);
    $zonefile = "$zoneDir/$zone.hosts";
    $newcontent = $_POST['zonecontent'];

    echo "<div class='dns-zone-editor'>";
    echo "<h3>Editing Zone: $zone</h3>";

    if (!file_exists($zonefile)) {
        echo "<div class='dns-error'>Zonefile not found: $zonefile</div>";
        echo "</div></div>";
        exit;
    }

    // bump serial
    $lines = explode("\n", $newcontent);
    $today = date("Ymd");
    $counter = "00";

    foreach ($lines as &$line) {
        if (preg_match('/\s+([0-9]{10})\s*;\s*serial/i', $line, $m)) {

            $oldSerial = $m[1];
            $oldDate   = substr($oldSerial, 0, 8);
            $oldCount  = substr($oldSerial, 8, 2);

            if ($oldDate === $today) {
                $counter = sprintf("%02d", intval($oldCount) + 1);
            }

            $newSerial = $today . $counter;
            $line = preg_replace('/[0-9]{10}/', $newSerial, $line);
            break;
        }
    }
    unset($line);

    $newcontent = implode("\n", $lines);

    if (!is_writable($zonefile)) {
        echo "<div class='dns-error'>Cannot write to $zonefile — check permissions.</div>";
    } else {

        $backupDir = "/var/named/chroot/var/named/backups";
        if (!is_dir($backupDir)) mkdir($backupDir, 0755, true);

        $timestamp  = date("Ymd_His");
        $backupFile = "$backupDir/{$zone}_$timestamp.hosts";

        copy($zonefile, $backupFile);
        file_put_contents($zonefile, $newcontent);

        $cmd = "named-checkzone " . escapeshellarg($zone) . " " . escapeshellarg($zonefile);
        $output = shell_exec($cmd . " 2>&1");

        if (strpos($output, "OK") === false) {
            echo "<div class='dns-error'>Zonefile validation failed:<br><pre>$output</pre></div>";
        } else {
            shell_exec("rndc reload " . escapeshellarg($zone));
            echo "<div class='dns-success'>Zonefile updated, serial bumped, validated, and reloaded.</div>";
        }
    }

    $content = htmlspecialchars($newcontent);

    echo <<<HTML
<form id="save-zone-form" method="POST">
    <textarea name="zonecontent" rows="20" style="width:100%;font-family:monospace;">$content</textarea>
    <input type="hidden" name="savezone" value="$zone">
    <button type="submit" class="btn-save">Save Changes</button>
    <button type="button" class="btn-restore" onclick="restoreLatestBackup()">Restore Latest Backup</button>
</form>
HTML;

    echo "</div></div>";
    exit;
}

/********************************************************************
 * 2️⃣ EDIT ZONE
 ********************************************************************/
if (isset($_POST['editzone'])) {

    $zone     = basename($_POST['editzone']);
    $zonefile = "$zoneDir/$zone.hosts";

    echo "<div class='dns-zone-editor'>";
    echo "<h3>Editing Zone: $zone</h3>";

    if (!file_exists($zonefile)) {
        echo "<div class='dns-error'>Zonefile not found: $zonefile</div>";
    } else {
        $content = htmlspecialchars(file_get_contents($zonefile));

        echo <<<HTML
<form id="save-zone-form" method="POST">
    <textarea name="zonecontent" rows="20" style="width:100%;font-family:monospace;">$content</textarea>
    <input type="hidden" name="savezone" value="$zone">
    <button type="submit" class="btn-save">Save Changes</button>
    <button type="button" class="btn-restore" onclick="restoreLatestBackup()">Restore Latest Backup</button>
</form>
HTML;
    }

    echo "</div></div>";
    exit;
}

/********************************************************************
 * 3️⃣ DEFAULT VIEW — DOMAIN LIST
 ********************************************************************/
echo "<h2>Domains</h2>";
echo "<div class='dns-domain-list'>";

foreach ($zones as $z) {
    $safe = htmlspecialchars($z);
    echo <<<HTML
<div class="dns-domain-item">
    <span class="dns-domain-name">$safe</span>
    <form class="edit-zone-form" method="POST">
        <input type="hidden" name="editzone" value="$safe">
        <button type="submit" class="btn-edit">Edit Zone</button>
    </form>
</div>
HTML;
}

echo "</div>";
echo "</div>";
?>

