<?php
require 'db.php';
require 'auth.php';
require_login();
require_admin();

echo "<h1>Test Delete Backup</h1>";

// Show current backup files
$backupDir = __DIR__ . DIRECTORY_SEPARATOR . 'backups';
if (is_dir($backupDir)) {
    $files = scandir($backupDir);
    echo "<h2>Current Backup Files:</h2>";
    echo "<ul>";
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..') {
            $filepath = $backupDir . DIRECTORY_SEPARATOR . $file;
            if (is_file($filepath)) {
                echo "<li>$file - " . filesize($filepath) . " bytes</li>";
            }
        }
    }
    echo "</ul>";
}

// Handle test delete
if (isset($_POST['test_delete']) && isset($_POST['filename'])) {
    $filename = basename($_POST['filename']);
    $filepath = $backupDir . DIRECTORY_SEPARATOR . $filename;
    
    echo "<h2>Delete Test Result:</h2>";
    echo "Attempting to delete: $filename<br>";
    echo "Full path: $filepath<br>";
    echo "File exists: " . (file_exists($filepath) ? 'YES' : 'NO') . "<br>";
    
    if (file_exists($filepath)) {
        if (unlink($filepath)) {
            echo "<p style='color: green;'>✅ File deleted successfully!</p>";
        } else {
            echo "<p style='color: red;'>❌ Failed to delete file!</p>";
        }
    } else {
        echo "<p style='color: orange;'>⚠️ File does not exist!</p>";
    }
    
    // Refresh file list
    echo "<p><a href='test-delete-backup.php'>Refresh</a></p>";
}

?>

<hr>
<h2>Test Delete Form:</h2>
<form method="POST">
    <label>Filename to delete:</label><br>
    <input type="text" name="filename" placeholder="e.g., before_restore_2025-08-24_16-41-18.sqlite" style="width: 400px;"><br><br>
    <button type="submit" name="test_delete" onclick="return confirm('Delete this file?')">Test Delete</button>
</form>

<p><a href="backup-restore.php">Back to Backup Restore</a></p>
