<?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, $pageSize);

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']);  // Decode the filename
        if (file_exists($fileToDelete)) {
            unlink($fileToDelete);
        }
        header("Location: files.php");  // Redirect to avoid re-posting on refresh
        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): ?>
            <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">&#x2B07;</a>
                <button onclick="deleteFile('<?php echo htmlspecialchars(rawurlencode($file)); ?>')" title="Delete">&#10060;</button>
            </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>
