<?php

$baseDir = realpath('/');

$currentDir = isset($_GET['dir']) ? realpath($_GET['dir']) : __DIR__;

if ($currentDir === false || !is_dir($currentDir)) {
    die("Erro: Diretório inválido.");
}

function removeDirectory($dir) {
    if (!is_dir($dir)) return false;
    $items = array_diff(scandir($dir), array('.', '..'));
    foreach ($items as $item) {
        $itemPath = $dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($itemPath)) {
            removeDirectory($itemPath);
        } else {
            unlink($itemPath);
        }
    }
    return rmdir($dir);
}

if (isset($_GET['file']) && !isset($_GET['action'])) {
    $file = basename($_GET['file']);
    $filePath = $currentDir . DIRECTORY_SEPARATOR . $file;
    if (is_file($filePath)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    } else {
        die("Erro: Arquivo não encontrado.");
    }
}

if (isset($_GET['action']) && $_GET['action'] == 'rename' && isset($_GET['item'])) {
    $item = basename($_GET['item']);
    $oldPath = $currentDir . DIRECTORY_SEPARATOR . $item;
    if (!file_exists($oldPath)) {
        die("Erro: Item não encontrado.");
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_name'])) {
        $newName = basename($_POST['new_name']);
        if (empty($newName)) {
            $error = "Nome inválido.";
        } else {
            $newPath = $currentDir . DIRECTORY_SEPARATOR . $newName;
            if (file_exists($newPath)) {
                $error = "Já existe um item com este nome.";
            } else {
                if (rename($oldPath, $newPath)) {
                    header("Location: ?dir=" . urlencode($currentDir));
                    exit;
                } else {
                    $error = "Erro ao renomear o item.";
                }
            }
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Renomear Item</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="container mt-4">
        <h2>Renomear: <?php echo htmlspecialchars($item); ?></h2>
        <?php if (isset($error)) echo '<div class="alert alert-danger">' . htmlspecialchars($error) . '</div>'; ?>
        <form method="POST">
            <div class="mb-3">
                <label for="new_name" class="form-label">Novo nome:</label>
                <input type="text" class="form-control" id="new_name" name="new_name" required>
            </div>
            <button type="submit" class="btn btn-primary">Renomear</button>
            <a href="?dir=<?php echo urlencode($currentDir); ?>" class="btn btn-secondary">Cancelar</a>
        </form>
    </body>
    </html>
    <?php
    exit;
}

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['create_dir']) && !empty($_POST['dir_name'])) {
        $newDir = $currentDir . DIRECTORY_SEPARATOR . basename($_POST['dir_name']);
        if (!file_exists($newDir)) {
            if (mkdir($newDir, 0755)) {
                $msg = "<div class='alert alert-success'>Diretório criado com sucesso.</div>";
            } else {
                $msg = "<div class='alert alert-danger'>Erro ao criar diretório.</div>";
            }
        } else {
            $msg = "<div class='alert alert-warning'>Diretório já existe.</div>";
        }
    }

    if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
        $uploadFile = $currentDir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
        if (file_exists($uploadFile)) {
            unlink($uploadFile);
        }
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
            $msg = "<div class='alert alert-success'>Arquivo enviado com sucesso.</div>";
        } else {
            $msg = "<div class='alert alert-danger'>Erro ao enviar arquivo.</div>";
        }
    }

    if (isset($_POST['delete'])) {
        $itemsToDelete = [];

        if (isset($_POST['selected_files']) && is_array($_POST['selected_files']) && $_POST['delete'] === 'bulk') {
            $itemsToDelete = $_POST['selected_files'];
        } else {
            $itemsToDelete[] = $_POST['delete'];
        }
        foreach ($itemsToDelete as $itemToDelete) {
            $itemToDelete = basename($itemToDelete);
            $targetPath = $currentDir . DIRECTORY_SEPARATOR . $itemToDelete;
            if (is_file($targetPath)) {
                unlink($targetPath);
            } elseif (is_dir($targetPath)) {
                removeDirectory($targetPath);
            }
        }
        $msg = "<div class='alert alert-success'>Item(s) excluído(s) com sucesso.</div>";
    }

    if (isset($_POST['download']) && isset($_POST['selected_files']) && is_array($_POST['selected_files'])) {
        $zipFile = tempnam(sys_get_temp_dir(), 'zip');
        $zip = new ZipArchive();
        if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
            foreach ($_POST['selected_files'] as $item) {
                $item = basename($item);
                $itemPath = $currentDir . DIRECTORY_SEPARATOR . $item;
                if (is_file($itemPath)) {
                    $zip->addFile($itemPath, $item);
                } elseif (is_dir($itemPath)) {
                    $files = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($itemPath, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::LEAVES_ONLY
                    );
                    foreach ($files as $file) {
                        $filePath = $file->getRealPath();
                        $relativePath = $item . '/' . substr($filePath, strlen($itemPath) + 1);
                        $zip->addFile($filePath, $relativePath);
                    }
                }
            }
            $zip->close();
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="arquivos_selecionados.zip"');
            header('Content-Length: ' . filesize($zipFile));
            readfile($zipFile);
            unlink($zipFile);
            exit;
        } else {
            $msg = "<div class='alert alert-danger'>Erro ao criar o arquivo ZIP.</div>";
        }
    }
}

$items = array_diff(scandir($currentDir), array('.', '..'));
sort($items);

function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return $bytes . ' byte';
    } else {
        return '0 bytes';
    }
}

$parentDir = dirname($currentDir);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Gerenciador de Arquivos</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .directory { font-weight: bold; }
    </style>
</head>
<body class="container mt-4">
    <h2>Gerenciador de Arquivos</h2>
    <?php if ($msg) echo $msg; ?>
    <p><strong>Diretório Atual:</strong> <?php echo htmlspecialchars($currentDir); ?></p>
    <div class="mb-3">
        <?php if ($currentDir !== "/"): ?>
            <a href="?dir=<?php echo urlencode($parentDir); ?>" class="btn btn-secondary">Voltar</a>
        <?php endif; ?>
        <a href="?dir=/" class="btn btn-secondary">Raiz</a>
    </div>

    
    <form method="POST" class="mb-3">
        <div class="input-group">
            <input type="text" name="dir_name" class="form-control" placeholder="Nome do novo diretório" required>
            <button type="submit" name="create_dir" class="btn btn-info">Criar Diretório</button>
        </div>
    </form>

    
    <form method="POST" enctype="multipart/form-data" class="mb-3">
        <div class="input-group">
            <input type="file" name="file" class="form-control" required>
            <button type="submit" class="btn btn-primary">Enviar Arquivo</button>
        </div>
    </form>

    
    <form method="POST">
        <table class="table table-striped">
            <thead class="table-dark">
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>Nome</th>
                    <th>Tamanho/Data</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                    <?php
                        $itemPath = $currentDir . DIRECTORY_SEPARATOR . $item;
                        $isDir = is_dir($itemPath);
                    ?>
                    <tr>
                        <td>
                            <input type="checkbox" name="selected_files[]" value="<?php echo htmlspecialchars($item); ?>">
                        </td>
                        <td>
                            <?php if ($isDir): ?>
                                <a href="?dir=<?php echo urlencode($itemPath); ?>" class="directory">[<?php echo htmlspecialchars($item); ?>]</a>
                            <?php else: ?>
                                <?php echo htmlspecialchars($item); ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            if ($isDir) {
                                echo date("d/m/Y H:i:s", filemtime($itemPath));
                            } else {
                                echo formatSize(filesize($itemPath));
                            }
                            ?>
                        </td>
                        <td>
                            <?php if (!$isDir): ?>
                                <a href="?file=<?php echo urlencode($item); ?>&dir=<?php echo urlencode($currentDir); ?>" class="btn btn-sm btn-success">Baixar</a>
                            <?php endif; ?>
                            <a href="?action=rename&item=<?php echo urlencode($item); ?>&dir=<?php echo urlencode($currentDir); ?>" class="btn btn-sm btn-warning">Renomear</a>
                            <button type="submit" name="delete" value="<?php echo htmlspecialchars($item); ?>" class="btn btn-sm btn-danger" onclick="return confirm('Tem certeza que deseja excluir este item?');">Excluir</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <button type="submit" name="delete" value="bulk" class="btn btn-danger" onclick="return confirm('Tem certeza que deseja excluir os itens selecionados?');">Excluir Selecionados</button>
        <button type="submit" name="download" class="btn btn-primary">Baixar Selecionados</button>
    </form>

    <script>
        document.getElementById('select-all').addEventListener('change', function() {
            var checkboxes = document.querySelectorAll('input[name="selected_files[]"]');
            for (var checkbox of checkboxes) {
                checkbox.checked = this.checked;
            }
        });
    </script>
</body>
</html>