<?php
// Define a simple hardcoded password for file deletion
define('DELETE_PASSWORD', '3268');

$directory = "a";
$files = array_diff(scandir($directory), array('..', '.'));
$pageSize = 30;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$totalPages = ceil(count($files) / $pageSize);
$displayFiles = array_slice($files, ($page - 1) * $pageSize);

$archiveDirectory = '/var/www/temp/ulbackups/';
$archiveLog = $archiveDirectory . 'archived_files.txt';

// Load archived files into an array
$archivedFiles = file_exists($archiveLog) ? file($archiveLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];

function formatFileName($filename) {
    return preg_replace('/^\d{8}_/', '', $filename);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($_POST['action'] == 'delete' && $_POST['password'] === DELETE_PASSWORD) {
        $fileToDelete = $directory . '/' . urldecode($_POST['filename']);
        if (file_exists($fileToDelete)) {
            unlink($fileToDelete);
        }
        header("Location: files.php");
        exit;
    } elseif ($_POST['action'] == 'archive' && $_POST['password'] === DELETE_PASSWORD) {
        $fileToArchive = $directory . '/' . urldecode($_POST['filename']);
        $archivePath = $archiveDirectory . basename($fileToArchive);
        // Only check if the file exists and then attempt to copy
        if (copy($fileToArchive, $archivePath)) {
            file_put_contents($archiveLog, basename($fileToArchive) . PHP_EOL, FILE_APPEND);
        } else {
            // Log an error if the copy fails
            error_log("Failed to copy file to $archivePath");
        }
        header("Location: files.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>File Viewer</title>
</head>
<body>
    <div class="file-list">
        <?php foreach ($displayFiles as $file): $isArchived = in_array($file, $archivedFiles); ?>
            <div class="file-entry">
                <span><?php echo htmlspecialchars(formatFileName($file)); ?></span>
                <button onclick="previewFile('<?php echo htmlspecialchars(rawurlencode($file)); ?>')" title="Preview">&#9654;</button>
                <a href="<?php echo $directory.'/'.rawurlencode($file); ?>" download title="Download">&nbsp;&#x2B07;&nbsp;</a>
                <button onclick="deleteFile('<?php echo htmlspecialchars(rawurlencode($file)); ?>')" title="Delete">&#10060;</button>
                <?php if (!$isArchived): ?>
                    <button onclick="archiveFile('<?php echo htmlspecialchars(rawurlencode($file)); ?>')" title="Archive">Archive</button>
                <?php else: ?>
                    <button disabled title="Archived">Archived</button>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
    <div id="modal" class="modal">
        <span class="close">&times;</span>
        <div class="content"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>