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

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

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

$zoneDir    = '/var/named/chroot/var/named';
$backupDir  = $zoneDir . '/backups';

/********************************************************************
 * 1️⃣ Validate input
 ********************************************************************/
if (!isset($_POST['restorezone'])) {
    echo "<div class='dns-error'>No zone specified.</div>";
    exit;
}

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

/********************************************************************
 * 2️⃣ Find latest backup
 ********************************************************************/
$pattern = "{$backupDir}/{$zone}_*.hosts";
$files   = glob($pattern);

if (!$files) {
    echo "<div class='dns-error'>No backups found for zone " . htmlspecialchars($zone) . ".</div>";
    exit;
}

sort($files);
$latestBackup = end($files);

/********************************************************************
 * 3️⃣ Restore backup
 ********************************************************************/
if (!copy($latestBackup, $zonefile)) {
    echo "<div class='dns-error'>Failed to restore backup file.</div>";
    exit;
}

/********************************************************************
 * 4️⃣ Validate restored zone
 ********************************************************************/
$validation = validate_zone($zone, $zonefile);

if (strpos($validation, 'OK') === false) {
    echo "<div class='dns-error'>Restored backup is invalid:<br><pre>" . 
         htmlspecialchars($validation) . "</pre></div>";
    exit;
}

/********************************************************************
 * 5️⃣ Reload zone in BIND
 ********************************************************************/
shell_exec("rndc reload " . escapeshellarg($zone));

/********************************************************************
 * 6️⃣ Output restored content
 ********************************************************************/
$content = htmlspecialchars(file_get_contents($zonefile));

echo "<div class='dns-success'>Latest backup restored and zone reloaded.</div>";

echo "
<div class='dns-zone-editor'>
    <h3>Editing Zone: " . htmlspecialchars($zone) . "</h3>
    <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='" . htmlspecialchars($zone) . "'>
        <button type='submit' class='btn-save'>Save Changes</button>
        <button type='button' class='btn-restore' onclick='restoreLatestBackup()'>Restore Latest Backup</button>
    </form>
</div>
";

